1. 程式人生 > >IN,NOT IN,ANY和ALL用於比較子查詢返回多行資料時你不知道的陷阱

IN,NOT IN,ANY和ALL用於比較子查詢返回多行資料時你不知道的陷阱

本文簡單講述一下在使用IN,NOT IN,ANY,ALL等對從子查詢中返回的資料做比較的時候一不小心就會犯的錯誤.
測試的的資料如下:TEST表中有3條資料,其中id為3的行name的值為null.
ID Name
1 name1
2 name2
3
1,IN在子查詢不返回資料的時候得到結果是false,這個比較容易理解.如下面的SQL不會查詢到資料.
select * from test  where name in (select name from test where id=4)
select * from test  where name =any (select name from test where id=4)
2,IN在子查詢返回的資料中有null值的時候,null不會用於比較,下面的語句只會返回id為2的行,id為3的行不會返回(null只能用is來比較)
select * from test  where name in (select name from test where id=3 or id=2)
select * from test  where name =any (select name from test where id=3 or id=2)
3,NOT IN在子查詢不返回資料的時候得到結果是true,下面的語句會返回3條資料.
select * from test  where name not in (select name from test where id=4)
!=ANY 通常可以替換 not in,但是在子查詢不返回行的時候是不相等的,下面的語句不返回任何行.(屬於第6條描述的情況)
select * from test  where name !=any (select name from test where id=4)
下面的語句效果相同
select * from test  where name not in (select name from test where id=2)
select * from test  where name !=any (select name from test where id=2)(屬於第7條描述的情況)
4,NOT IN 在子查詢返回的資料中有null值的時候,不會返回資料,如下面的SQL不會將id為1的行查詢出來.
select * from test  where name not in (select name from test where id=3 or id=2)
!=ANY在子查詢有null值返回的時候,null值忽略,下面的SQL返回ID=1的行
select * from test  where name !=any (select name from test where id=3 or id=2)
5,ANY和ALL不能和IN一起用,它們只能和通常用於單行比較的運算子,如<,<=,>等一起用.
6,ANY在子查詢不返回資料的時候得到結果是false,如下面的語句不會返回資料.
select * from test  where name < any (select name from test where id=4)
7,在子查詢返回的資料中有null值的時候,null不會用於比較,下面的語句只會返回id為1的行,id為3的行不會返回(null只能用is來比較)
select * from test  where name < any (select name from test where id=3 or id=2)
8,ALL在子查詢不返回資料的時候得到結果是true,如下面的語句會返回3行資料.
select * from test  where name < all (select name from test where id=4)
9,ALL在子查詢返回的資料中有null值的時候,不會返回資料.
select * from test  where name < all (select name from test where id=3 or id=2)