mysql子查询

1. where 型子查询
如题:在goods表中查到最大的价格的一条商品

 select * from goods order by shop_price desc limit 1; (排序一般都比较消耗资源)

以上语句也可以用where型子查询来完成。

 select * from goods where shop_price=(select max(shop_price) from goods);

这里的条件shop_price用后面的select语句来获取。

select * from goods where shop_price in (select max(shop_price) from goods  group by cat_id  );
--获取每个栏目下的最贵的商品信息

这里写图片描述

2. from 型子查询
每次查询出来的结果还是可以当成一张表来看。接下去上面的例子:
将上面的查询出来的结果集可以被查询。

 select * from (select * from goods where shop_price in (select max(shop_price) from goods  group by cat_id )) as mytable where goods_id>20;

需要注意的是一定要加上as 表名
否者会报错:Every derived table must have its own alias
这句话的意思是说每个派生出来的表都必须有一个自己的别名

这里写图片描述

3. exists 型子查询
如题:用exists型子查询,查出所有不存在商品的栏目
分析:如果有商品那么 select * from goods where cat_id=”栏目id” 能够找到商品。

select * from category where not exists(select * from goods where goods.cat_id=category.cat_id);

以上语句分析:在栏目表中查询所有想要的字段信息,条件是栏目中的cat_id 在商品表中的不存在。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值