在尝试隔离下面第一个查询中的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中的布尔表达式计算结果为true
或false
或null
。
任何SQL语句的WHERE
子句都会过滤掉布尔表达式/条件为而不是的所有行。true
,即过滤掉false
和null
所有布尔表达式:
null != ''
null = ''
null not in ('A', 'H')
被计算为null
(demo),因为任何将/与null
进行比较而不使用IS
运算符返回null
。
这就是为什么您的第2,3d和第4查询不仅过滤掉不满足
WHERE
子句中的条件的行,而且过滤掉c
是null
的行。如果你想要这些行c
是null
,你必须明确地提到:
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 ''