首頁  >  文章  >  每日程式設計  >  not exists用法

not exists用法

anonymity
anonymity原創
2019-04-26 09:37:0085470瀏覽

not exists是sql中的一個語法,常用在子查詢和主查詢之間,用於條件判斷,根據一個條件返回一個布林值,從而來確定下一步操作如何進行,not exists也是exists或in的對立面。

not exists用法

not exists 是exists的對立面,所以要了解not exists的用法,我們先了解下exists、in的差異和特點:

exists : 強調的是是否返回結果集,不要求知道返回什麼, 例如:

select name from student where sex = 'm' and mark exists(select 1 from grade where ...)

只要exists引導的子句有結果集返回,那麼exists這個條件就算成立了,大家注意返回的字段總是1,如果改成“select 2 from grade where ...”,那麼傳回的欄位就是2,這個數字沒有意義。所以exists子句不在乎回傳什麼,而是在乎是不是有結果集回傳。

而exists 與in 最大的區別在於in引導的子句只能返回一個字段,例如:

select name from student where sex = 'm' and mark in (select 1,2,3 from grade where ...)

in子句返回了三個字段,這是不正確的,exists子句是允許的,但in只允許有一個字段返回,在1,2,3中隨便去了兩個字段。

而not exists 和not in 分別是exists 和 in 的 對立面。

exists     (sql       返回结果集,为真)

主要看exists括號中sql語句的結果是否有結果,有結果:才會繼續執行where條件;沒結果:視為where條件不成立。

not exists   (sql       不返回结果集,为真)

主要看not exists括號中的sql語句是否有結果,無結果:才會繼續執行where條件;有結果:視為where條件不成立。

not exists:經過測試,當子查詢和主查詢有關聯條件時,相當於從主查詢中去掉子查詢的資料。

not exists用法

例如:

test資料:id  name

                  1     e

select * from test c where  not exists
(select 1 from test t where t.id= '1' )
--无结果

以上是not exists用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn