oracle常識(一) in和exist的區別

2021-08-25 07:22:16 字數 1762 閱讀 2978

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
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適合於外表小而內錶大的情況

原文:

Oracle 入門常識

認識oracle資料庫 oracle 甲骨文 公司發展史 1977年,三人合夥創辦 software development laboratories,sdl 1979年,更名為relational software inc.rsi 1983年,為了突出核心產品 rsi更名為oracle 2002年...

ORACLE基本常識

個表空間只能屬於乙個資料庫 每個資料庫最少有乙個控制檔案 建議3個,分別放在不同的磁碟上 每個資料庫最少有乙個表空間 system表空間 建立system表空間的目的是盡量將目的相同的表存放在一起,以提高使用效率 每個資料庫最少有兩個聯機日誌檔案 乙個資料檔案只能屬於乙個表空間 乙個資料檔案一旦被加...

oracle小常識整理

一 if.then.elsif.then.end if if nodelimit 12節 and node1 1 then istimevalid true elsif nodelimit 34節 and node1 2 then istimevalid true elsif nodelimit 5...