理解在groupby和WHERE子句中如何处理NULL ?



在尝试隔离下面第一个查询中的7行时,我得到了作为新手没有预料到的结果。我阅读了这个SQLite文档,但不明白为什么在第一个查询中,GROUP BY中分隔了7行NULL,但是对!= '',not in ('A','H')=''的测试都排除了NULL行。

看起来好像测试是排他性的,因此NULL是=''!='',或in ('A','H')not in ('A','H')。它似乎被所有这些都忽略了,但在GROUP by中被分隔开。

你能解释一下它为什么这样工作吗?

谢谢。

sqlite> select substr(trim(grammarCode),1,1) as c, count(indexRow) as cnt
from tbl
group by c
order by cnt;
c  cnt   
-  ------
7     
A  4828  
20046 
H  300679
sqlite> select substr(trim(grammarCode),1,1) as c, count(indexRow) as cnt
from tbl
where c != ''
group by c
order by cnt;
c  cnt   
-  ------
A  4828  
H  300679
sqlite> select substr(trim(grammarCode),1,1) as c, count(indexRow) as cnt
from tbl
where c not in ('A', 'H')
group by c
order by cnt;
c  cnt   
-  ------
20046 
sqlite> select substr(trim(grammarCode),1,1) as c, count(indexRow) as cnt
from tbl
where c = ''
group by c
order by cnt;
c  cnt   
-  ------
20046 
sqlite> select substr(trim(grammarCode),1,1) as c, count(indexRow) as cnt
from tbl
where c is null
group by c
order by cnt;
c  cnt   
-  ------
7     

SQL中的布尔表达式计算结果为truefalsenull

任何SQL语句的WHERE子句都会过滤掉布尔表达式/条件为而不是的所有行。true,即过滤掉falsenull

所有布尔表达式:

null != ''
null = ''
null not in ('A', 'H')

被计算为null(demo),因为任何将/与null进行比较而不使用IS运算符返回null


这就是为什么您的第2,3d和第4查询不仅过滤掉不满足WHERE子句中的条件的行,而且过滤掉cnull的行。

如果你想要这些行cnull,你必须明确地提到:

c != '' OR c IS NULL
c = '' OR c IS NULL
c not in ('A', 'H') OR c IS NULL

或者,对于前两种情况,您可以使用操作符IS:

c IS NOT ''
c IS ''

最新更新