一、子查詢的分類
1. 按位置分為
where 子查詢:子查詢在where條件中
from 子查詢:子查詢在from后面
exists子查詢:子查詢在exists中
2. 按查詢結果分為
標量子查詢:查詢結果有一行一列
列子查詢:查詢結果有一列多行
行子查詢:查詢結果有一行多列或多行多列
表子查詢:查詢結果有多行多列並且出現的位置在from之后
二、子查詢詳解
1. 標量子查詢
-- 已知學生表my_stu和班級表my_class, 查詢class001班中的所有學生,查詢結果是一個ID,一行和列
select * from my_stu where class_id = (select id from my_class where c_name = 'class001');
2. 列子查詢
-- 查詢所有存在的班級內的學生
select * from my_stu where class_id in (select id from my_class);
-- 類似in的其他條件關鍵字, 都必須帶 = 號
select * from my_stu where class_id = any(select id from my_class); -- 等於其中任意一個就保留
select * from my_stu where class_id = some(select id from my_class); -- 等於其中一部分就保留
select * from my_stu where class_id = all (select id from my_class); -- 等於其中所有的才保留
3. 行子查詢
-- 查詢學生中年齡最大且身高最高的
select * from my_stu where age = (select max(age) from my_stu) and height = (select max(height) from my_stu); -- 常規查詢
select * from my_stu where (age,height) = (select max(age),max(height) from my_stu); -- 構造行元素來使用行子查詢
4. 表子查詢
-- 找出每個班最高的一個學生
select * from (select * from my_stu order by height desc) as s group by class;
5. exists子查詢
exists接在where之后, 返回0或1.
select * from my_student where exists(select * from my_class where id = 1);