in 與 exist 的語法比較:
? ?? ?? ? select × from 數據表 t where t.x in (...)
? ?? ?括號內可以是符合t.x字段類型的值集合,如('1','2','3'),但如果t.x是number類型的時候,似乎這樣的寫法會出問題;也可以是通 過另外的select語句查詢出來的值集合,如(select y from 數據表2 where ...)。
? ?? ?? ? select * from 數據表 t where [...] and exist (...)
? ?? ?方括號內為其它的查詢條件,可以沒有。exist后面的括號內可以是任意的條件,這個條件可以與外面的查詢沒有任何關系,也可以與外面的條件結合。如: (select * from 數據表2 where 1=1) 或 (select * from 數據表2 where y=t.x)
例子:
in的SQL語句
SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime
FROM tab_oa_pub WHERE is_check=1 and
category_id in (select id from tab_oa_pub_cate where no='1')
order by begintime desc
exists的SQL語句
SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime
FROM tab_oa_pub WHERE is_check=1 and
exists (select id from tab_oa_pub_cate where tab_oa_pub.category_id=convert(int,no) and no='1')
order by begintime desc
?
效率比較:
? ?? ???先討論IN和EXISTS。
? ?? ?? ?? ?select * from t1 where x in ( select y from t2 )
? ?? ???事實上可以理解為:
? ?? ?? ?? ?select * from t1, ( select distinct y from t2 ) t2 where t1.x = t2.y
? ?? ?? ?如果你有一定的SQL優化經驗,從這句很自然的可以想到t2絕對不能是個大表,因為需要對t2進行全表的“唯一排序”,如果t2很大這個排序的性能是不 可忍受的。但是t1可以很大,為什么呢?最通俗的理解就是因為t1.x=t2.y可以走索引。但這并不是一個很好的解釋。試想,如果t1.x和t2.y都 有索引,我們知道索引是種有序的結構,因此t1和t2之間最佳的方案是走merge join。另外,如果t2.y上有索引,對t2的排序性能也有很大提高。
? ?? ?? ?? ?select * from t1 where exists ( select null from t2 where y = x )
? ?? ???可以理解為:
? ?? ?? ?? ?for x in ( select * from t1 )
? ?? ?? ?? ?loop
? ?? ?? ?? ?? ? if ( exists ( select null from t2 where y = x.x ) then
? ?? ?? ?? ?? ?? ? OUTPUT THE RECORD!
? ?? ?? ?? ?? ? end if
? ?? ?? ?? ?end loop
? ?? ???這個更容易理解,t1永遠是個表掃描!因此t1絕對不能是個大表,而t2可以很大,因為y=x.x可以走t2.y的索引。
? ?? ???綜合以上對IN/EXISTS的討論,我們可以得出一個基本通用的結論:IN適合于外表大而內表小的情況;EXISTS適合于外表小而內表大的情況。