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 在商品表中的不存在。