为什么sqlite通过查询分组返回count(*)的null?

时间:2019-07-22 09:33:57

标签: sql sqlite

如果我进行简单查询,则为:

select count(*) from emails
where id <= 0

它返回一行零。

但是,如果我按查询分组,则表示:

select count(*) from emails
where id <= 0
group by emails.id

它不返回任何行。

为什么行为会有所不同,以及如何修改第二个查询以实现与第一个查询相同的行为?

命令行输出:

sqlite> select count(*) from emails where id <= 0;
0
sqlite> select count(*) from emails where id <= 0 group by emails.id;
sqlite> 

3 个答案:

答案 0 :(得分:0)

使用条件聚合:

select count(case when id <= 0 then 1 end) as cnt
from emails;

WHERE子句的问题在于,根本没有记录具有id <= 0的记录,结果集中将没有任何内容。

答案 1 :(得分:0)

这是因为re.fullmatch(checksum_regex, samplehex) 不存在任何行,因此与id<=0匹配的表中的行恰好为0行,而尝试id<=0时则没有行显示。

答案 2 :(得分:0)

您的第一个查询是不带group by的聚合查询:

select count(*)
from emails
where id <= 0;

这样的查询总是 保证能返回恰好一行。即使表为空或所有行都被滤除,整个行集也被视为单个组。发生这种情况时,COUNT()返回0。大多数其他聚合函数(也许都是聚合函数)返回NULLCOUNT()从不返回NULL

您的第二个查询:

select count(*)
from emails
where id <= 0
group by emails.id;

是带有GROUP BY的聚集查询 。对于GROUP BY键描述的每组值,此查询返回一行。在这种情况下,没有组,因为所有行都被过滤掉了。因此,这根本不返回任何行。