小编给大家分享一下MySQL查询数据之合并查询结果的案例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
.
利用union关键字,可以给出多条select语句,并将它们的结果组合成单个结果集。合并时,两个表对应的列数和数据类型必须相同。各个select语句之间使用union或union all 关键字分隔。
union不使用关键字all,执行的时候删除重复的记录,所有返回的行都是唯一的;使用关键字all的作用是不删除重复行也不对结果进行自动排序。
基本语法格式为:
select column,...from table1union [all]select column,... from table2
【例1】查询所有价格小于9的水果的信息,查询s_id等于101和103所有的水果的信息,使用union连接查询结果,sql语句如下:
MysqL> select s_id,f_name,f_price -> from fruits -> where f_price <9.0 -> union all -> select s_id,f_name,f_price -> from fruits -> where s_id in(101,103);+------+------------+---------+| s_id | f_name | f_price |+------+------------+---------+| 104 | lemon | 6.40 || 101 | apple | 5.20 || 103 | apricot | 2.20 || 104 | Berry | 7.60 || 107 | xxxx | 3.60 || 105 | melon | 8.20 || 101 | cherry | 3.20 || 105 | xbabay | 2.60 || 102 | grape | 5.30 || 107 | xbabay | 3.60 || 101 | apple | 5.20 || 103 | apricot | 2.20 || 101 | blackBerry | 10.20 || 101 | cherry | 3.20 || 103 | coconut | 9.20 |+------+------------+---------+15 rows in set (0.06 sec)
union将多个select语句的结果组合成一个结果集合。可以分开查看每个select语句的结果:
MysqL> select s_id,f_name,f_price -> from fruits -> where f_price < 9.0;+------+---------+---------+| s_id | f_name | f_price |+------+---------+---------+| 104 | lemon | 6.40 || 101 | apple | 5.20 || 103 | apricot | 2.20 || 104 | Berry | 7.60 || 107 | xxxx | 3.60 || 105 | melon | 8.20 || 101 | cherry | 3.20 || 105 | xbabay | 2.60 || 102 | grape | 5.30 || 107 | xbabay | 3.60 |+------+---------+---------+10 rows in set (0.00 sec)MysqL> select s_id,f_name,f_price -> from fruits -> where s_id in(101,103);+------+------------+---------+| s_id | f_name | f_price |+------+------------+---------+| 101 | apple | 5.20 || 103 | apricot | 2.20 || 101 | blackBerry | 10.20 || 101 | cherry | 3.20 || 103 | coconut | 9.20 |+------+------------+---------+5 rows in set (0.00 sec)
由分开查询结果可以看到,第1条select语句查询价格小于9的水果,第2条select语句查询供应商101和103提供的水果。
【例2】查询所有价格小于9的水果的信息,查询s_id等于101和103的所有水果的信息,使用union all连接查询结果,sql语句如下:
MysqL> select s_id,f_name,f_price -> from fruits -> where f_price<9.0 -> union all -> select s_id,f_name,f_price -> from fruits -> where s_id in(101,103);+------+------------+---------+| s_id | f_name | f_price |+------+------------+---------+| 104 | lemon | 6.40 || 101 | apple | 5.20 || 103 | apricot | 2.20 || 104 | Berry | 7.60 || 107 | xxxx | 3.60 || 105 | melon | 8.20 || 101 | cherry | 3.20 || 105 | xbabay | 2.60 || 102 | grape | 5.30 || 107 | xbabay | 3.60 || 101 | apple | 5.20 || 103 | apricot | 2.20 || 101 | blackBerry | 10.20 || 101 | cherry | 3.20 || 103 | coconut | 9.20 |+------+------------+---------+15 rows in set (0.00 sec)
可以看到,这里总的记录等于两条select语句返回的记录数之和,连接查询结果并没有去除重复的行。
union和union all的区别:
以上是“MySQL查询数据之合并查询结果的案例”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程之家行业资讯频道!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。