.
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教學(影片)
#
以上是MySQL查詢資料之合併查詢結果的詳細內容。更多資訊請關注PHP中文網其他相關文章!