SQL 中exists的用法

2021-06-19 23:28:45 字數 2618 閱讀 7803

比如在northwind資料庫中有乙個查詢為

select c.customerid,companyname from customers c

where exists(

select orderid from orders o where o.customerid=c.customerid) 

這裡面的exists是如何運作呢?子查詢返回的是orderid欄位,可是外面的查詢要找的是customerid和companyname欄位,這兩個字段肯定不在orderid裡面啊,這是如何匹配的呢? 

exists用於檢查子查詢是否至少會返回一行資料,該子查詢實際上並不返回任何資料,而是返回值true或false

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

語法: exists subquery

引數: subquery 是乙個受限的 select 語句 (不允許有 compute 子句和 into 關鍵字)。

結果型別: boolean 如果子查詢包含行,則返回 true ,否則返回 flase 。

例表a:tablein

例表b:tableex

(一). 在子查詢中使用 null 仍然返回結果集

select * from tablein where exists(select null)

等同於: select * from tablein

(二). 比較使用 exists 和 in 的查詢。注意兩個查詢返回相同的結果。

(三). 比較使用 exists 和 = any 的查詢。注意兩個查詢返回相同的結果。

not exists 的作用與 exists 正好相反。如果子查詢沒有返回行,則滿足了 not exists 中的 where 子句。

結論:exists(包括 not exists )子句的返回值是乙個bool值。 exists內部有乙個子查詢語句(select ... from...), 我將其稱為exist的內查詢語句。其內查詢語句返回乙個結果集。 exists子句根據其內查詢語句的結果集空或者非空,返回乙個布林值。

一種通俗的可以理解為:將外查詢表的每一行,代入內查詢作為檢驗,如果內查詢返回的結果取非空值,則exists子句返回true,這一行行可作為外查詢的結果行,否則不能作為結果。

分析器會先看語句的第乙個詞,當它發現第乙個詞是select關鍵字的時候,它會跳到from關鍵字,然後通過from關鍵字找到表名並把表裝入記憶體。接著是找where關鍵字,如果找不到則返回到select找欄位解析,如果找到where,則分析其中的條件,完成後再回到select分析字段。最後形成一張我們要的虛表。

where關鍵字後面的是條件表示式。條件表示式計算完成後,會有乙個返回值,即非0或0,非0即為真(true),0即為假(false)。同理where後面的條件也有乙個返回值,真或假,來確定接下來執不執行select。

分析器先找到關鍵字select,然後跳到from關鍵字將student表匯入記憶體,並通過指標找到第一條記錄,接著找到where關鍵字計算它的條件表示式,如果為真那麼把這條記錄裝到乙個虛表當中,指標再指向下一條記錄。如果為假那麼指標直接指向下一條記錄,而不進行其它操作。一直檢索完整個表,並把檢索出來的虛擬表返回給使用者。exists是條件表示式的一部分,它也有乙個返回值(true或false)。

在插入記錄前,需要檢查這條記錄是否已經存在,只有當記錄不存在時才執行插入操作,可以通過使用 exists 條件句防止插入重覆記錄。

insert into tablein (aname,a***) 

select top 1 '張三', '男' from tablein

where not exists (select * from tablein where tablein.aid = 7)

exists與in的使用效率的問題,通常情況下採用exists要比in效率高,因為in不走索引,但要看實際情況具體使用:

in適合於外表大而內錶小的情況;exists適合於外表小而內錶大的情況。

SQL中EXISTS的用法

比如在northwind資料庫中有乙個查詢為 select c.customerid,companyname from customers c where exists select orderid from orders o where o.customerid c.customerid 這裡面的...

SQL中EXISTS的用法

比如在northwind資料庫中有乙個查詢為 select c.customerid,companyname from customers c where exists select orderid from orders o where o.customerid c.customerid 這裡面的...

SQL中EXISTS的用法

比如在northwind資料庫中有乙個查詢為 select c.customerid,companyname fromcustomers c where exists select orderid fromorders owhereo.customerid c.customerid 這裡面的exis...