.
select column,...from table1union [all]select column,... from table2
(免费学习推荐:mysql视频教程)
【例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的区别:
union all
的功能是不删除重复行,all关键字语句执行时所需要的资源少, 所以尽可能的使用它。更多相关免费学习推荐:mysql教程(视频)
Atas ialah kandungan terperinci MySQL查询数据之合并查询结果. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!