您的位置:首页 > 数据库 > MySQL

MySQL数据库总结(4)子查询与联合

2016-03-13 12:36 357 查看
1子查询
1Where 型子查询 把内层查询的作为外层查询的比较条件

2From 型子查询 把内层的查询结果当成临时表供外层sql再次查询

3Exists 型子查询外层sql查询的代入内层sql查询要使内层查询能够成立 查询可以与in型子查询互换但效率要高

Union联合

1、子查询:

子查询就是在原有的查询语句中,嵌入新的查询,来得到我们想要的结果集。一般根据子查询的嵌入位置分为,where型子查询,from型子查询

1、Where 型子查询: 把内层查询的作为外层查询的比较条件

典型语法:

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

2、From 型子查询: 把内层的查询结果当成临时表,供外层sql再次查询

给临时表加一个别名 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;

3、Exists 型子查询:外层sql查询的代入内层sql查询,要使内层查询能够成立 。查询可以与in型子查询互换,但效率要高.

典型语法:

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 、Union:联合

作用: 把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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: