MySQL 查询结果令人困惑。当单独选择年份时,它给出的计数大于 1,但总体而言不是

问题描述 投票:0回答:1
mysql> select count(distinct message_id) from table1 where message_notification=0 and YEAR(created_at) = '2024';

| count(distinct message_id) |
|                         33 |


mysql> select count(distinct message_id) from table1 where message_notification=0 and YEAR(created_at) = '2023';

| count(distinct message_id) |
|                       5796 |

1 row in set (0.07 sec)

mysql> select count(distinct message_id) from table1 where message_notification=0 and YEAR(created_at) = '2022';

| count(distinct message_id) |
|                        431 |

1 row in set (0.03 sec)

加431+5796+33=6260

但是

mysql> select count(distinct message_id) from table1 where message_notification=0;
| count(distinct message_id) |
|                       6259 |

1 row in set (0.05 sec)

没有created_at NULL或message_notification NULL的记录。
没有创建时间为 2021 年或以下的记录。
没有创建时间为 2024 年或更大的记录。
通过选择created_at asc和desc来检查

mysql mysql-5.7
1个回答
0
投票

我认为这里的问题是

distinct
部分。如果您有两行(或更多行)具有相同的
message_id
但在不同的年份,它们将单独出现在各个年份的查询中,但在跨年份查询时将被视为一行。

如果将年份添加到

distinct
子句中,您应该得到“预期”6260:

select count(distinct message_id, YEAR(created_at)) 
-- Here --------------------------^
from   table1 
where  message_notification=0;
© www.soinside.com 2019 - 2024. All rights reserved.