一、子查询的执行顺序:
严格的执行顺序:where > group by > having > order by > limit
二、where 子查询
解释:内层的查询结果作为外层的SQL的筛选条件
1.案例:查出序号(goods_id)最大的商品信息(goods_id、goods_name),goods 表部分结构如下:
采用非子查询的方法:
//排序很消耗系统资源,不推荐
SELECT goods_id,goods_name FROM goods ORDER BY goods_id DESC LIMIT 1;
采用 WHERE 子查询的方法:
SELECT goods_id,goods_name from goods WHERE goods_id = (SELECT MAX(goods_id) FROM goods);
2.案例:查出每种商品分类(cat_id)下商品序号(goods_id)最大的商品信息,goods 表结构同上
采用 WHERE 子查询解决:
SELECT goods_id,cat_id,goods_name FROM goods WHERE goods_id IN (SELECT max(goods_id) FROM goods GROUP BY cat_id);
采用右链接的方式解决:
SELECT goods.cat_id,goods_id,goods.goods_name FROM goods RIGHT JOIN
(SELECT cat_id,MAX(goods_id) AS mg FROM goods GROUP BY cat_id) taa ON mg = goods_id;
三、from 型子查询
解释:内层的查询的结果集,当成外层SQL的原始表数据进行查询
案例:在以商品分类(cat_id)升序、商品序号(goods_id)降序排序的结果集中,查出前5个商品的信息,goods 表结构如下:
采用 from 子查询方式:
SELECT goods_id,cat_id,goods_name FROM (SELECT * FROM goods ORDER BY cat_id ASC,goods_id DESC) AS tmp LIMIT 0,5;
四、exists 型子查询
案例:在 category 表中查询出那些出现在 goods 表中的cat_id,显示分类名称(cat_name),category表和goods表如下:
采用 exists 子查询:
select cat_id,cat_name from category
where exists(select * from goods where goods.cat_id = category.cat_id);