Mysql 多态关系中的subselect出现意外结果
有人能解释一下为什么我在这两个问题上得到如此奇怪的结果,因为我自己都搞不懂 Mysql版本:8.0.18 我在两台完全不同的机器上用相同的Mysql版本Ubuntu 16.04和Ubuntu20.04进行了测试 共有两个表格: 产品:Mysql 多态关系中的subselect出现意外结果,mysql,polymorphic-associations,mysql-8.0,Mysql,Polymorphic Associations,Mysql 8.0,有人能解释一下为什么我在这两个问题上得到如此奇怪的结果,因为我自己都搞不懂 Mysql版本:8.0.18 我在两台完全不同的机器上用相同的Mysql版本Ubuntu 16.04和Ubuntu20.04进行了测试 共有两个表格: 产品: | id | name | |----|-----------| | 1 | product 1 | | 2 | product 2 | | 3 | product 3 | | 4 | product 4 | 评论: | id | comme
| 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查询,一切正常:
选择
`id`,
选择
计数*
从…起
`评论`
哪里
`产品`.`id`=`comments`.`commentable\u id`
和“comments”。“commentable_type`='Product”
和“comments”。“confirmed_at”不为空
因为“评论”很重要`
从…起
`产品`
哪里
`1,2,3,4中的id`
结果:
| id | comments_count |
|----|----------------|
| 1 | 2 |
| 2 | 2 |
| 3 | 0 |
| 4 | 2 |
| id | comments_count |
|----|----------------|
| 1 | 2 |
| 2 | 2 |
| 3 | 0 |
| 4 | 0 |
通过此SQL查询,我得到了非常奇怪的结果:
选择
`id`,
选择
计数*
从…起
`评论`
哪里
`产品`.`id`=`comments`.`commentable\u id`
和“comments”。“commentable_type`='Product”
和“comments”。“confirmed_at”不为空
将1限制为“评论数”`
从…起
`产品`
哪里
`1,2,3,4中的id`
结果:
| id | comments_count |
|----|----------------|
| 1 | 2 |
| 2 | 2 |
| 3 | 0 |
| 4 | 2 |
| id | comments_count |
|----|----------------|
| 1 | 2 |
| 2 | 2 |
| 3 | 0 |
| 4 | 0 |
在这种情况下,DISTINCT和LIMIT都没有意义。您有一个标量子查询,即:始终返回1行。我无法重现您的问题:抱歉,不应该有DISTINCT我删除了iti。我正在尝试不同的方案,但忘记删除DISTINCT。我知道不应该有限制1,我只是想弄清楚,为什么Mysql会返回如此奇怪的结果。它可能与mysql设置或其他相关吗?因为在其他机器上,一切都按预期进行。我输入了您的所有数据并测试了您的两个查询。它们返回与上述示例数据相同的结果。我建议您对未显示的其他查询或未显示的其他数据有问题。我刚刚录制了视频: