网站建设首页怎么弄,wordpress 分页太慢,北京视频网站建设,wordpress 关闭某个插件的更新文章目录一、语法说明exists#xff1a;not exists#xff1a;二、常用示例说明1.查询a表在b表中存在数据2.查询a表在b表中不存在数据3.查询时间最新记录4.exists替代distinct剔除重复数据总结一、语法说明
exists#xff1a;
括号内子查询sql语句返回结果不为空#xff…
文章目录一、语法说明existsnot 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.查询a表在b表中存在数据
相当于sql中in操作。
select * from a where exists (select 1 from b where a_ida.id )以上sql等价于下面的sql
select * from a where id in (select a_id from b)2.查询a表在b表中不存在数据
相当于sql中not in操作。
select * from a where not exists (select 1 from b where a_ida.id )以上sql等价于下面的sql
select * from a where id not in (select a_id from b)3.查询时间最新记录
以下sql查询同一id内的c_date最近的记录。
SELECT * FROM c t1 WHERE NOT EXISTS(select * from c where id t1.id and c_datet1.c_date)分析子查询中先看id 1 的情形只有当t1.c_date 取最大值时没有返回结果因为是NOT EXISTS关键字所以Where条件成立返回符合条件的查询结果
4.exists替代distinct剔除重复数据
例如下面sql
SELECT distinct a.id,a.name from a, b WHERE a.idb.a_id;使用exists提出重复等价于上面的sql
select id,name from a where exists (select 1 from b where a_ida.id );分析RDBMS 核心模块将在子查询的条件一旦满足后立即返回结果所以自带去重
总结
word文档下载地址sql语句中exists用法详解