in 和exits 的區別

2021-05-24 05:06:34 字數 1807 閱讀 9997

sql中in,not in,exists,not exists的用法和差別:

in:確定給定的值是否與子查詢或列表中的值相匹配。

in 關鍵字使您得以選擇與列表中的任意乙個值匹配的行。

當要獲得居住在 california、indiana 或 maryland 州的所有作者的姓名和州的列表時,就需要下列查詢:

select productid, productname from northwind.dbo.products where categoryid = 1 or categoryid = 4 or categoryid = 5

然而,如果使用 in,少鍵入一些字元也可以得到同樣的結果:

select productid, productname from northwind.dbo.products where categoryid in (1, 4, 5)

in 關鍵字之後的專案必須用逗號隔開,並且括在括號中。

下列查詢在 titleauthor 表中查詢在任一種書中得到的版稅少於 50% 的所有作者的 au_id,然後從 authors 表中選擇 au_id 與

titleauthor 查詢結果匹配的所有作者的姓名:

select au_lname, au_fname from authors where au_id in (select au_id from titleauthor where royaltyper < 50)

結果顯示有一些作者屬於少於 50% 的一類。

not in:通過 not in 關鍵字引入的子查詢也返回一列零值或更多值。

以下查詢查詢沒有出版過商業書籍的出版商的名稱。

select pub_name from publishers where pub_id not in (select pub_id from titles where type = 'business')

使用 exists 和 not exists 引入的子查詢可用於兩種集合原理的操作:交集與差集。兩個集合的交集包含同時屬於兩個原集合的所有元素。

差集包含只屬於兩個集合中的第乙個集合的元素。

exists:指定乙個子查詢,檢測行的存在。

本示例所示查詢查詢由位於以字母 b 開頭的城市中的任一出版商出版的書名:

select distinct pub_name from publishers where exists (select * from titles where pub_id = publishers.pub_id and type =

'business')

select distinct pub_name from publishers where pub_id in (select pub_id from titles where type = 'business')

兩者的區別:

exists:後面可以是整句的查詢語句如:select * from titles

in:後面只能是對單列:select pub_id from titles

not exists:

例如,要查詢不出版商業書籍的出版商的名稱:

select pub_name from publishers where not exists (select * from titles where pub_id = publishers.pub_id and type =

'business')

下面的查詢查詢已經不銷售的書的名稱:

select title from titles where not exists (select title_id from sales where title_id = titles.title_id)

Sql語句中in和exits的區別

小明 in select sname from student 等同於exists select from student where sname 小明 這兩個涵數是差不多的,但是由於優化方案的不同,通常not exists要比not in 要快,因為not exists可以使用結合演算法,而not...

mysql中IN和EXITS效率

mysql中的in語句是把外表和內錶作hash 連線。而exists語句是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。一直大家都覺得exists比in語句的效率要高。這樣的說法事實上是不準確的。這個是要區分環境的。假設查詢的兩個表大小相當,那麼用in和exists區別不大。假設兩個表中乙...

理解null如何影響in和exits語句

從表面上看,in和exits的sql語句是可互換和等效的。然而,它們在處理uull資料時會有很大的差別,並導致不同的結果。問題的根源是在乙個oracle資料庫中,乙個null值意味著未知變數,所以操作null值的比較函式的結果也是乙個未知變數,而且任何返回null的值通常也被忽略。例如,以下查詢都不...