子查詢,即子選擇、嵌套查詢、嵌套選擇;
子查詢在邏輯上一般是兩個查詢(內查詢、外查詢);
使用子查詢的好處是,原本需要多個查詢語句可以用一個查詢完成,缺點是內查詢不支持索引,所以一般會引起性能問題。
1、按照結果集,對子查詢可以分為:
① 標量子查詢
通常與比較運算符一起使用,返回的是一個具體值。
② 行子查詢
通常與 = 操作符一起使用,返回的是一行數據。
③ 列子查詢
通常與 in 操作符一起使用,返回的是一列數據。
④ 表子查詢
通常返回 M 到 N 行數據。
2、按照語句,對子查詢可以分為:
① 用在 where 子句中的叫 where 型子查詢
比如:
select * from aa where id > (select max(id) from bb);
select * from aa where id in (select id from bb);
select * from aa where id,name in (select id,name from bb);
② 用在 from 子句中的叫 from 型子查詢
比如:
select * from (select * from bb where id > 10) as B where name like "%shang%";
③ 用在 exists 子句中的叫 exists 型子查詢
如果內查詢為 true,那么外查詢顯示出來,比如:
select * fom aa where exists(select * from bb where bb.id = aa.id);
ps:使用字段時指定表名。