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

问题描述

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

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 (将#修改为@)