当前位置:   article > 正文

sql语句中exists用法详解_sql exists

sql exists


一、语法说明

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 核心模块将在子查询的条件一旦满足后,立即返回结果,所以自带去重

总结

word文档下载地址:sql语句中exists用法详解

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/851875
推荐阅读
相关标签
  

闽ICP备14008679号