子查询就是在原有的查询语句中,嵌入新的查询,来得到我们想要的结果集。一般根据子查询的嵌入位置分为,where型子查询,from型子查询
典型语法:
select * from tableName
where colName = (select colName from tbName where ….)
{where colName in (select colName from tbName where ..)}
典型题:查询最大商品,最贵商品
查询出最新一行商品(以商品编号最大为最新,用子查询实现)
select goods_id,goods_name from goods where goods_id=(select max(goods_id) from goods);
每个栏目最贵的商品
Select goods_id,cat_id,goods_name,shop_price from goods where shop_price in (select max(shop_price) from goods group by cat_id);
给临时表加一个别名 as
典型语法:
select * from (select * from tableName where …) where….
典型题:查询栏目下最新/最贵商品
试查询两门及两门以上不及格同学的平均分(where、from子查询)
select name,avg(score) from stu where name in (select name from (select name,sum(score<60) as h from stu group by name having h>1) as tmp) group by name;
典型语法:
select * from tablename
where exists(select * from tableName where …)
典型题:查询有商品的栏目
Select cat_id,cat_name from category where exists (select * from goods where goods.cat_id = category.cat_id);
作用: 把2次或多次查询结果合并起来
要求:两次查询的列数一致
推荐:查询的每一列,相对应得列类型也一样
可以来自于多张表,多次sql语句取出的列名可以不一致,此时,以第1个sql的列名为准
如果不同的语句中取出的行,有完全相同的(每个列的值都相同),那么相同的行将会合并(去重复).
如果不去重复,可以加all来指定 union all
想取第4栏目的商品,价格降序排列,还想取第5栏目的商品,价格也降序排列
(select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 4 order by shop_price desc) union (select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 5 order by shop_price desc) order by shop_price desc;
取第3个栏目价格前3高的商品和第4个栏目价格前2高的商品,union来实现
(Select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 3 order by shop_price desc limit 3) union
(Select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 4 order by shop_price desc limit 2)