Where型子查询:指把内层查询的结果作为外层查询的比较条件
案例:查出每一个栏目下面最新的商品
select goods_id,cat_id,goods_name from goods where goods_id in (select max(goods_id) from goods group by cat_id);
From型子查询:把内层的查询结果当成临时表,供外层SQL再次查询
案例:同上题
select * from (select goods_id,cat_id,goods_name from goods order by cat_id asc,goods_id desc) as tmp group by cat_id;
思考:如何用子查询查出挂科两门及以上同学的平均分,where型,from型都可以
select name,avg(score) from stu where name in (select name from ( select name,count(*) as gk from stu where score < 60 group by name having gk >= 2) as tmp) group by name;
上例,我们用where+from型子查询,得出挂科2门及以上同学的成绩。
Exits子查询:
把外层的查询结果代入到内层,看内层是否成立。如果内层成立,就把这个结果取出来,如果内层不成立,那就把这个结果丢弃。
两张表:
Category和goods表
Category表里面的内容如下:
案例:不把9个栏目全部取出来,只把栏目下面有商品的给取出来
select cat_id,cat_name from category where exists (select * from goods where goods.cat_id=category.cat_id);
我们假设category表下面的栏目cat_id的值为1,那我们把这个值代入到select * from goods where goods.cat_id=category.cat_id语句当中就变成了select * from goods where goods.cat_id=1;如果这个语句是空的,那么它就会丢弃,不是空的它就会取出来。