1. 程式人生 > 資料庫 >SQL exists 基本用法

SQL exists 基本用法

SQL exists 基本用法

最近重新用到了 exists關鍵字,對於其基本用法記錄一下。

1、基本用法

exists用於where後的子查詢中,如果子查詢有返回值,則返回 true, 否則返回 false,不返回子查詢的 select 欄位值。

user 表

id  name
1   tes1
2   test2
3   test3

address 表

id  city    user_id 
1   廣州市    2
2   汕頭市    3

user 表與 address 表為一對多的關係。

示例

現在查詢 city = '廣州市' 的使用者,那麼寫法可以如下:

select u.id, u.name
from user u 
where exists(select a.id from address a where a.city='廣州市' and a.user_id = u.id )

exists返回 boolean 值,因而子查詢中返回欄位不做限制。

查詢結果如下:

id  name
2   test2