1.where型子查詢:
select cat_id,good_id,good_name from goods where good_id in (selct max(good_id) from goods group by cat_id);
2. from 型子查詢:
select * from (select cat_id,good_id,good_name from goods order by cat_id asc, good_id desc) as temp group by cat_id;
3.from和where型綜合練習:
查出掛科2門及以上同學的平均分:
思路講解:
select c.name ,avg(c.score) from cenjibiao c,(select name ,count(*) from cejibiao where score < 60 group by name having count(*)>=2) t where c.name = t.name group by c.name ; ;
4.in子查詢:查詢年齡為20歲的員工部門
select * from department where did in(SELECT did from employee where age=20);
5.exists子查詢:查詢是否存在年齡大於21歲的員工
select * from department where EXISTS (SELECT did from employee where age>21);
6. all子查詢:查詢滿足條件的部門
select * from department where did> all(SELECT did from employee );
7比較運算符子查詢:查詢趙四是哪個部門的
select * from department where did= all(SELECT did from employee where name='趙四');
總結:
where型子查詢:指把內部查詢的結果作為外層查詢的比較條件。
from型子查詢:把內層的查詢結果當成臨時表,供外層sql再次查詢。
in子查詢:內層查詢語句僅返回一個數據列,這個數據列的值將供外層查詢語句進行比較。
exists子查詢:把外層的查詢結果,拿到內層,看內層是否成立,簡單來說后面的返回true,外層(也就是前面的語句)才會執行,否則不執行。
any子查詢:只要滿足內層子查詢中的任意一個比較條件,就返回一個結果作為外層查詢條件。
all子查詢:內層子查詢返回的結果需同時滿足所有內層查詢條件。
比較運算符子查詢:子查詢中可以使用的比較運算符如 “>” “<” “= ” “!=”
來自:https://blog.csdn.net/qq_39380737/article/details/81127497