SQL中EXISTS的用法

2021-06-19 11:46:31 字數 2146 閱讀 3315

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

select c.customerid, companyname fromcustomers c

where exists(

select orderid fromorders owhereo.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 的查詢。注意兩個查詢返回相同的結果。

select * from tablein where exists(select bid from tableex where bname=tablein.aname)

select * from tablein where aname in(select bname from tableex)

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

select * from tablein where exists(select bid from tableex where bname=tablein.aname)

select * from tablein where aname=any(select bname from tableex)

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

結論:

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

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

在插入記錄前,需要檢查這條記錄是否已經存在,只有當記錄不存在時才執行插入操作,可以通過使用 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 from customers c where exists select orderid from orders o where o.customerid c.customerid 這裡面的...