七、union联合

Union:联合
作用:把2次或多次查询结果合并起来
案例(认识union):我想把商品价格大于5000元的和商品价格小于20元的商品都取出来
1.Select * from goods where shop_price < 20 or shop_price >5000;
2.我们用union将他们合并就是
Select * from goods where shop_price < 20
Select * from goods where shop_price > 5000
然后用个union将他们联合一下就行了
Select * from goods where shop_price < 20 union Select * from goods where shop_price > 5000
 
Union的语法要求:
两次查询的列数一致
推荐:最好查询的每一列,相对应的列类型也一样。
 
可以来自于多张表
多次sql语句取出的列名可以不一致,此时以第1sql的列名为准。
 
面试题:
有两张表
1张为
Ta
 
Id num
a   5
b  10
c  15
d  10
 
 
Tb
 
Id    num
b     5
c    10
d    20
e    99
 
想得到的结果
a,5
b,15
c,25
d,30
e,99
 
select id,sum(num) from (select * from ta union select * from tb) as tmp group by id;
 
如果不同的语句中取出的行,有完全相同(即每个列的值都相同,例上例中我把tb表的C的值也改为15,那就和ta表完全相同了),那么相同的行将会合并(即去重复)。
 
如果不去重复,可以加all来指定。
select * from ta union all select * from tb;
同理,我想完成上一题,现在我的C的值是15了,而不是10
Ta
 
Id num
a,  5
b,  10
c,  15
d,  10
 
 
Tb
 
Id   num
b    5
c    15
d    20
e    99
 
这个时候语句就是这样,在union后面加个all就行了
select id,sum(num) from (select * from ta union all select * from tb) as tmp group by id;
现在一个新题目:
想取出第4栏目的商品,价格降序排列,还想取出第5个栏目的商品,价格也降序排列,用union完成。
(select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 4) union (select goods_id,cat_id,goods-name,shop_price from goods where cat_id = 5) order by shop_price;
如果子句中有order by,limit,需加小括号()括起来,推荐放到所有子句之后,即对最终合并后的结果来排序。
 
取第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);
在子句中,order by 配合limit使用才有意义,如果order by 不配合limit使用,会被语法分析器优化分析时,去除。