mysql学习--union

union:合并两条或者多条语句的结果

语法:sql1 union sql2

1、问:能否从2张表查询再union呢?
答:可以,union合并的是结果集,不区分来自哪一张表。但是如果两张表列的名字不一样的话就要统一。

select user_name,msg_content,msg_time from feedback where msg_status=1
union
select user_name,content as msg_content,add_time as msg_timme from comment where status=1;

2、问:取自2张表,通过别名让2个结果集列一致。那么如果取出的结果集,列名字不一样,是否还能union。
答:能,以第一句sql中的列名称为准

select user_name,msg_content,msg_time from feedback where msg_status=1
union
select user_name,content ,add_time  from comment where status=1;

3、问:union满足什么条件就可以使用?
答:只要结果集中列的个数一致就行,就算列的类型不一样也可以合并。

4、问:union后的结果集是否可以排序?
答:可以,在后面加上order by就行了,注意,order by是针对合并后的结果集进行排序。

5、问:如果union后的结果有重复行(既有2行或者N行所有列的值都一样),怎么办?
答:默认去重,如果不想去重,使用union all
在这里插入图片描述
上述两张表sname的值一样

select * from test12
union
select * from test13;

在这里插入图片描述

select * from test12
union all
select * from test13;

在这里插入图片描述

练习
1、用union取出第四个栏目和第五个栏目的商品,并按照价格升序排列

select goods_name,cat_id,shop_price from goods where cat_id=4
union
select goods_name,cat_id,shop_price from goods where cat_id=5
order by shop_price asc;

在这里插入图片描述
2、思考下面的sql语句

(select goods_name,cat_id,shop_price from goods where cat_id=4 order by shop_price desc)
union
(select goods_name,cat_id,shop_price from goods where cat_id=5 order by shop_price desc)
order by shop_price asc;

在这里插入图片描述
内层语句的排序毫无意义,因为外层语句还要对最终结果再次排序
如果内层的order by语句单独使用时,不会影响结果集仅仅是排序的话,在执行期间就被MySQL的代码分析器优化掉了。内层的order by语句必须在能够影响结果集时,才有意义,比如配合limit使用。

3、查出第3个栏目下,价格前3高的商品和第4个栏目下,价格前2高的商品,用union完成。

(select cat_id,goods_name,shop_price from goods where cat_id=3 order by shop_price desc limit 3)
union
(select cat_id,goods_name,shop_price from goods where cat_id=4 order by shop_price desc limit 2);

在这里插入图片描述
这一次的sql语句中,内层的排序发挥了作用,因为有limit,order会实际影响结果集,有意义。

4、要求查出价格低于100元和价格高于4000元的商品

select goods_name,shop_price from goods where shop_price < 100 
union  
select goods_name,shop_price  from goods  where shop_price >4000;

在这里插入图片描述
5、union经典面试题
在这里插入图片描述
把A\B两表对应id的num值相加。

select id,sum(num) from 
((select * from a) union (select * from b)) as tmp 
group by id;

在这里插入图片描述

发布了20 篇原创文章 · 获赞 0 · 访问量 223

猜你喜欢

转载自blog.csdn.net/alyssa_yu/article/details/104877421