首页 > 技术文章 > SQL exists 基本用法

CF1314 2020-12-28 18:00 原文

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

推荐阅读