你可能会有这样的困惑,当你想查询某个字段是null的数据集时,你写下
select * from table where column = null
这样显然是行不通的。正确写法如下:
select * from table where column is null
那么,为什么要这样设定的?
今天在写一条子查询语句的时候我就体会到了这样设定的好处,这条子查询如下:
select t.* from table1 t
where t.acct_id = (select acct_id from table2 where staff_id = 'xxx')
当我写下这句时,我就在考虑,如果子查询里得到的结果是null怎么办?
如果是子查询里的结果为null,那么我预期的结果自然应该是查不出任何数据,因为 table1 中有许多acct_id为null的数据,所以我担心会把那些数据给查出来。那我是不是要加一句条件防止这种情况呢?
select t.* from table1 t
where t.acct_id = (select acct_id from table2 where staff_id = 'xxx')
-- 新加的条件
and exists (select 1 from table2 where staff_id = 'xxx')
我尝试了一下,发现是这样做是没有必要的。
正如我开篇所说:select * from table where column = null 是查不出任何结果的。
也许正是为了避免这样无谓的条件,所以才区分开 is null 和 = null