首先聲明:數據庫高手請走開,您看了礙眼啊!
有些時候進行查詢的時候啊,一個字段的in、 not in根本不能滿足要求,非常需要類似多個字段的in、not in,但是很多數據庫不支持多個字段的in、 not in (DB2是支持的),估計也讓不少朋友們郁悶吧!不過沒關系,我這不寫文章了嘛,呵呵!
我用過的數據庫有Access,SQL Server,DB2,見笑見笑啊!其實也就SQL Server,DB2這兩個還像點樣點兒,呵呵……,言歸正傳啊
首先聲明DB2是支持多個字段 in、 not in的
先說基本情況:
數據庫:DB2 8.2,SQL Server 2005 Express
表a 有字段:aaa,bbb,還可能有其他字段。記錄條數:3764
表b 有字段:aaa,bbb,還可能有其他字段。記錄條數:4127
夠明顯了吧,就是表a的字段aaa跟表b的字段aaa有對應關系,就是表a字段的bbb跟表b的字段bbb有對應關系。
但是只有aaa,bbb兩個字段都同時對應上了才算是真的對應上了。(也不知道我說的清不清楚,理解萬歲啊)
好了,開始正文:
1. 先說“in”。
從表b里查詢出滿足條件“select aaa,bbb from a”的記錄:
如下語句就是我們想要的結果:
select * from b where (aaa,bbb) in ( select aaa,bbb from a );
不過很可惜,上面的語句只能再DB2上執行,SQL Server不行。(其他數據庫沒有試過,不知道啊!)
還好可以用下面的語句來代替
select * from b where exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb);
當然你可能會說我的條件是“select aaa,bbb from a where 表a某字段1='...' and 表a某字段2>1111” 什么等等,我就權且用“查詢條件A”代表了
即:查詢條件A = 表a某字段1='...' and 表a某字段2>1111
那語句就該這么寫了
select * from b where (aaa,bbb) in ( select aaa,bbb from a where 查詢條件A);
select * from b where exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb and 查詢條件A);
用exists時,最好把“查詢條件A”中的“表a某字段1”之類寫為“a.表a某字段1”。原因自己想啊。
2. 再說“not in”。基本和“in”一樣,我就直接復制過來了,偷個懶啊
從表b里查詢出不在結果集“select aaa,bbb from a”中的記錄:
如下語句就是我們想要的結果:
select * from b where (aaa,bbb) not in ( select aaa,bbb from a );
不過很可惜,上面的語句只能再DB2上執行,SQL Server不行。(其他數據庫沒有試過,不知道啊!)
還好可以用下面的語句來代替
select * from b where not exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb);
當然你可能會說我的條件是“select aaa,bbb from a where 表a某字段1='...' and 表a某字段2>1111” 什么等等,我就權且用“查詢條件A”代表了
即:查詢條件A = 表a某字段1='...' and 表a某字段2>1111
那語句就該這么寫了
select * from b where (aaa,bbb) not in ( select aaa,bbb from a where 查詢條件A);
select * from b where not exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb and 查詢條件A);
用not exists時,最好把“查詢條件A”中的“表a某字段1”之類寫為“a.表a某字段1”。原因自己想啊。
ok,說完了,下面就幾個方面比較一下吧(雖然意義不是很大,呵呵)
寫法上:
當然是in、not in最直觀了(地球人都知道)。
再說效率問題(僅限DB2,原因不用說了吧):
in效率比exists高
not exists效率比not in高
具體執行時間如下
in 0.01 secs
exists 0.03 secs
not in 8.62 secs
not exists 0.03 secs
總結:
多字段in、not in在db2數據中可以執行,SQL Server不行。(其他數據庫沒有試過,不知道!)
exists、not exists在db2,SQL Server均可執行。(其他數據庫沒有試過,不知道!)
而且總體上用exists,not exists 效率都很高,建議大家還是用好exists,not exists吧!
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/moklee/archive/2009/01/07/3730282.aspx