測試必備的Mysql常用sql語句系列
https://www.cnblogs.com/poloyy/category/1683347.html
前言
- 子查詢在我們查詢方法中是比較常用的,通過子查詢可以實現多表查詢
- 子查詢是指:將一個查詢語句嵌套在另一個查詢語句中
- 子查詢可以在select、update、delete語句中使用,還可以進行多層嵌套
子查詢的語法格式
WHERE <表達式> <操作符> (子查詢)
語法格式說明
- 操作符可以是比較運算符、in、not in、exists、not exists
- not 當然就是取反啦
in 和 exists的一個比較
in | exists |
當表達式與子查詢返回的結果集中的某個值相等時,返回 TRUE,否則返回 FALSE; | 用於判斷子查詢的結果集是否為空,若子查詢的結果集不為空,返回 TRUE,否則返回 FALSE; |
適合外表大而內表小的情況 | 適合內表大而外表小的情況 |
無論哪個表大,用 not exists 都比 not in 速度快 |
|
1、A是表達式,B是子查詢結果集 2、若A在B里面,則返回True |
|
方便理解,畫個圖 |
先看看dept、emp表有什么數據
dept表
emp表
比較運算符的栗子
查詢部門是銷售部的員工信息
select * from emp where dept_id = (select id from dept where name = "銷售部")
查詢部門不是銷售部的員工信息
select * from emp where dept_id <> (select id from dept where name = "銷售部")
in 的栗子
SQL分析
- 從 dept 表查詢部門名字為銷售部or財務部的部門 id
- 然后從 emp 表查詢 depte_id 在上面 id 結果集的記錄
select * from emp where dept_id in (select id from dept where name = "財務部" or name ="銷售部")
可以看看子查詢 sql 的查詢結果
select id from dept where name = "財務部" or name ="銷售部"
最終的 sql 其實是這樣的
select * from emp where dept_id in (1,3)
not in 的栗子
select * from emp where dept_id not in (select id from dept where name = "財務部" or name ="銷售部")
其實就是上面栗子結果集的取反
exists 栗子
SQL分析
- 從 dept 表中查詢 id = 1 的記錄,若有,exists 表達式則返回True
- 外層查詢語句接收到 True 之后,對 emp 表進行查詢,返回所有記錄
select * from emp where exists(select * from dept where id = 1)
可以看看 exists 表達式里的子查詢結果集
select * from dept where id = 1
可以看到,查詢結果集不為空,所以 exists() 返回 true
最終的 sql 其實是這樣的
select * from emp where true
exists + 其他查詢條件的栗子
select * from emp where exists (select * from dept where id = 1) and dept_id = 2
知識點
- 子查詢的功能其實通過表連接(join)也可以完成
- 一般來說,表連接(內連接、外連接等)都可以用子查詢查詢,但反過來卻不一定,有的子查詢不能用表連接來替換
- 子查詢比較靈活,適合作為查詢的篩選條件
- 表連接更適合查看連接表之后的數據集