sql语句中exists用法详解

文章目录
一、语法说明
exists:
not exists:
二、常用示例说明
1.查询a表在b表中存在数据
2.查询a表在b表中不存在数据
3.查询时间最新记录
4.exists替代distinct剔除重复数据
总结
一、语法说明
exists:
括号内子查询sql语句返回结果不为空(即:sql返回的结果为真),子查询的结果不为空这条件成立,执行主sql,否则不执行。

not exists:
与exists相反,括号内子查询sql语句返回结果为空(即:sql不返回的结果为真),子查询的结果为空则条件成立,执行主slq,否则不执行。
总结:exists 和not exists语句强调是否返回结果集,不要求知道返回什么,与in的区别就是,in只能返回一个字段值,exists允许返回多个字段。

二、常用示例说明
创建示例数据,如下代码a表和b表为一对多关系。以下sql使用改示例数据。

create table a(
id int,
name varchar(10)
);
insert into a values(1,'data1');
insert into a values(2,'data2');
insert into a values(3,'data3');

create table b(
id int,
a_id int,
name varchar(10)
);
insert into b values(1,1,'info1');
insert into b values(2,2,'info2');
insert into b values(3,2,'info3');

create table c(
id int,
name varchar(10),
c_date TIMESTAMP
);
insert into c values(1,'c1','2023-02-21 17:01:00');
insert into c values(2,'c2','2023-02-21 17:02:00');
insert into c values(2,'c3','2023-02-21 17:03:00');

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1.查询a表在b表中存在数据
相当于sql中in操作。

select * from a where exists (select 1 from b where a_id=a.id )
1
以上sql等价于下面的sql

select * from a where id in (select a_id from b)
1
2.查询a表在b表中不存在数据
相当于sql中not in操作。

select * from a where not exists (select 1 from b where a_id=a.id )
1
以上sql等价于下面的sql

select * from a where id not in (select a_id from b)
1
3.查询时间最新记录
以下sql查询同一id内的c_date最近的记录。

SELECT * FROM c t1
WHERE NOT EXISTS(select * from c where id = t1.id and c_date>t1.c_date)
1
2
分析:子查询中,先看id = 1 的情形,只有当t1.c_date 取最大值时,没有返回结果,因为是NOT EXISTS关键字,所以Where条件成立,返回符合条件的查询结果

4.exists替代distinct剔除重复数据
例如下面sql

SELECT distinct a.id,a.name from a, b WHERE a.id=b.a_id;
1
使用exists提出重复,等价于上面的sql

select id,name from a where exists (select 1 from b where a_id=a.id );
1
分析:RDBMS 核心模块将在子查询的条件一旦满足后,立即返回结果,所以自带去重
————————————————
版权声明:本文为CSDN博主「小马穿云」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ma286388309/article/details/129279863

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章