union(联合)合并查询结果

 select  id,name,price from shops where price > 150  union select id,name,price from shops  where price<50

作用:把两次或多次查询结果合并在一起,可以来自多张表,多次sql语句时取出的列明不同,此时以第一个sql列明为准

要求两次查询的列数一致

推荐:查询的每一列对应的列的类型也相同,比如char类型和tinyint类型,会自动转换为blob二进制

如果不同语句中取出的行有完全相同(每个列的值都相同),那么相同的行将会合并(去重复)如果不去重复,可以加all不去重复

select  id,name,price from shops where price > 150  union all select id,name,price from shops  where price<50

如果语句中有order  by  limit等,需要用括号包起来,推荐把order by放到全部语句最后,对最终合并后的结果排序,才能发挥排序作用,如:(select  id,name,price from shops where price > 150  order by id desc) union all (select id,name,price from shops  where price<50 order by id desc)  order by id desc;

在子句中如果order by 不配合limit使用,会被语法分析器优化分析时去掉

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值