微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多态关系中带有子选择的意外结果

如何解决多态关系中带有子选择的意外结果

有人能解释一下为什么我在这两个查询中得到如此奇怪的结果,因为我自己无法弄清楚。

MysqL版本:8.0.18

我在两台完全相同的MysqL版本(Ubuntu 16.04和Ubuntu 20.04)的机器上对此进行了测试

有两个表:

产品:

| id | name      |
|----|-----------|
| 1  | product 1 | 
| 2  | product 2 |
| 3  | product 3 |
| 4  | product 4 |

评论

| id | commentable_id | commentable_type | content | confirmed_at        |
|----|----------------|------------------|---------|---------------------|
| 1  | 1              | Product          | test    | 2020-11-02 01:00:00 |
| 2  | 1              | Product          | test    | 2020-11-02 01:00:00 |
| 3  | 2              | Product          | test    | 2020-11-02 01:00:00 |
| 4  | 2              | Product          | test    | 2020-11-02 01:00:00 |
| 5  | 3              | Product          | test    | null                |
| 6  | 4              | Product          | test    | 2020-11-02 01:00:00 |
| 7  | 4              | Product          | test    | 2020-11-02 01:00:00 |

使用此SQL查询,一切正常:

SELECT 
    `id`,(SELECT 
           COUNT(*)
        FROM
            `comments`
        WHERE
            `products`.`id` = `comments`.`commentable_id`
                AND `comments`.`commentable_type` = 'Product'
                AND `comments`.`confirmed_at` is not null
        ) AS `comments_count`
FROM
    `products`
WHERE
    `id` IN (1,2,3,4)

结果:

| id | comments_count |
|----|----------------|
| 1  | 2              | 
| 2  | 2              |
| 3  | 0              |
| 4  | 2              |

通过此SQL查询,我得到非常奇怪的结果:

SELECT 
    `id`,(SELECT 
           COUNT(*)
        FROM
            `comments`
        WHERE
            `products`.`id` = `comments`.`commentable_id`
                AND `comments`.`commentable_type` = 'Product'
                AND `comments`.`confirmed_at` is not null
        LIMIT 1) AS `comments_count`
FROM
    `products`
WHERE
    `id` IN (1,4)

结果:

| id | comments_count |
|----|----------------|
| 1  | 2              | 
| 2  | 2              |
| 3  | 0              |
| 4  | 0              |

Mysql workbench recorded

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。