你真的会玩SQL吗?系列目录
此文是继文章 EXISTS代替in
EXISTS和IN之间的区别
1.EXISTS只返回TRUE或FALSE,不会返回UNKNOWN。
2.IN当遇到包含NULL的情况,那么就会返回UNKNOWN。
当查询的列包含NULL时,NOT EXISTS正常返回TRUE或FALSE。
而NOT IN可能返回空集,如下
1:val IN(val1,val2,...,NULL),永远不会返回FALSE,而是返回TRUE或UNKNOWN。
2:val NOT IN(val1,val2,...,NULL),永远不会返回TRUE,而是返回NOT TRUE或NOT UNKNOWN。
看个示例:
Test1表
select t.[name] from Test as t
where exists (select t1.orderid from Test1 as t1 where t1.[name]=t.[name])
返回 aaa,ccc,ddd
select t.[name] from Test as t
where t.[name] in (select t1.[] from Test1 as t1)
返回 aaa,ccc,ddd
select t.[name] from Test as t
where not exists (select t1.orderid from Test1 as t1 where t1.[name]=t.[name])
返回 bbb
select t.[name] from Test as t
where t.[name] not in (select t1.[name] from Test1 as t1)
返回空集
练习
以下对就返回哪三值?
答案
