您的位置:首页 > 数据库 > MySQL

mysql 子查询

2014-05-07 14:31 141 查看
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);也行

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: