1.使用where子查询
查询每个栏目下最新的商品:(最终查询结果是多行 内层sql返回是多行单列)
select goods_id,goods_name,cat_id from goods where goods_id in (select max(goods_id) from goods group by cat_id );
查询(所有栏目中)最新的商品:(最终查询结果是单行 内层sql返回单行单列)
select goods_id,goods_name,cat_id from goods where goods_id = (select ma
x(goods_id) from goods );
总结:
注意区分上述两个应用以及语句。
where子查询,是指把内层sql查询的结果作为外层查询的比较条件
典型的就是查询最新的商品,最贵的商品
如果 where 列 =(内层sql) 则内层sql只返回‘单行单列,单个值’
如果 where 列in(内层sql) 则内层sql只返回‘单列,可以多行’
2.使用from子查询
查询每个栏目下最新的商品:
select * from (select goods_id,goods_name,cat_id from goods order by cat_id asc,goods_id desc ) as tmp group by cat_id;
注意:一定要有as tmp 否则语法错误Every derived table must have its own alias:每个派生出来的表都要有自己的别名。
3.exists子查询
只把category中的里面有商品的栏目取出来
select cat_id,cat_name from category where exists (select * from goods wh
ere goods.cat_id = category.cat_id);
select cat_id,cat_name from category where exists (select * from goods wh
ere cat_id = category.cat_id);也行