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

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