mysql 子查询


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);也行






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值