MySQL exists的用法介紹

2021-06-18 12:02:47 字數 1289 閱讀 3090

有乙個查詢如下:

select c.customerid, companyname   

from customers c

where exists(

select orderid from orders o

where o.customerid = cu.customerid)

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

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

exists 指定乙個子查詢,檢測行的存在。語法:exists subquery。引數 subquery 是乙個受限的 select 語句 (不允許有 compute 子句和 into 關鍵字)。結果型別為 boolean,如果子查詢包含行,則返回 true。

又比如以下 sql 語句:

select distinct 姓名 from xs

where not exists (

select * from kc

where not exists (

select * from xs_kc

where 學號=xs.學號 and 課程號=kc.課程號

))

中間的 exists 語句只做出對上一層的返回 true 或 false,因為查詢的條件都在 where 學號=xs.學號 and 課程號=kc.課程號這句話裡。每乙個 exists 都會有一行值。它只是告訴一層,最外層的查詢條件在這裡成立或都不成立,返回的時候值也一樣回返回上去。直到最高層的時候如果是 true(真)就返回到結果集。為 false(假)丟棄。把最外層的查詢xs裡的資料一行一行的做裡層的子查詢。

where not exists

select * from xs_kc

where 學號=xs.學號 and 課程號=kc.課程號

這個 exists 就是告訴上一層,這一行語句在我這裡不成立。因為他不是最高層,所以還要繼續向上返回。

select distinct 姓名 from xs where not exists (這裡的 exists 語句收到上乙個為 false 的值。他在判斷一下,結果就是為 true(成立),由於是最高層所以就會把這行的結果(這裡指的是查詢條件)返回到結果集。

原文:

MySQL exists的用法介紹

有乙個查詢如下 1selectc.customerid,companyname 2fromcustomers c 3whereexists 4selectorderidfromorders o 5whereo.customerid cu.customerid 這裡面的exists是如何運作呢?子查詢...

MySQL exists的用法介紹

有乙個查詢如下 1 select c.customerid,companyname 2 from customers c 3 where exists 4 select orderid from orders o 5 where o.customerid cu.customerid 這裡面的exis...

Mysql exists用法小記

exists用於檢查子查詢是否至少會返回一行資料,該子查詢實際上並不返回任何資料,而是返回值true或false。exists 指定乙個子查詢,檢測行的存在。語法 exists subquery。引數 subquery 是乙個受限的 select 語句 不允許有 compute 子句和 into 關...