慎用not in 和 all 表達式

當連接列或比較列有null空值,用 not in 和 <> all 表達式會過濾掉連接列或比較列值爲null的記錄(雖然連接列或比較列爲null,但這條記錄的其它列是非空的),這樣可能就取不了自己本意想要的記錄,用 not exists 表達式可以規避這個問題,如下:


04:21:56 SYS@orcl*SQL > select * from t1;



                COL1 CO
-------------------- --
                   1 A
                   2 B
                   3 C
                   4


Elapsed: 00:00:00.01
04:21:59 SYS@orcl*SQL > select * from t2;


CO COL3
-- ----
A  A2
B  B2
D  D2


Elapsed: 00:00:00.01
04:22:02 SYS@orcl*SQL > select * from t1 where col2 not in (select col2 from t2);


                COL1 CO
-------------------- --
                   3 C


Elapsed: 00:00:00.01
04:22:08 SYS@orcl*SQL > select * from t1 where col2 <> any (select col2 from t2);


                COL1 CO
-------------------- --
                   1 A
                   2 B
                   3 C


Elapsed: 00:00:00.01
04:22:14 SYS@orcl*SQL > select * from t1 where not exists (select 1 from t2 where col2=t1.col2);


                COL1 CO
-------------------- --
                   3 C
                   4
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章