1 union 的作用
union 運算符用于組合兩個或更多 select 語句的結果集。
2 union 使用前提
union 中的每個 select 語句必須具有相同的列數
- 這些列也必須具有相似的數據類型
- 每個 select 語句中的列也必須以相同的順序排列
3 union 語法
select column_name(s) from table1
union
select column_name(s) from table2;
注釋:默認情況下,union 運算符選擇一個不同的值。如果允許重復值,請使用union all。
4?UNION ALL 語法
union all
select column_name(s) from table2;
5 示例數據
以下是"customers" 表中的數據:
csdn=> select * from customers;id | name | addr | city | zip | province
----+--------+---------------+------+--------+----------1 | 魯智深 | 北京路27號 | 平涼 | 200000 | 甘肅省2 | 李四 | 南京路12號 | 杭州 | 310000 | 浙江市3 | 王五 | 花城大道17號 | 廣州 | 510000 | 廣州省4 | 馬六 | 江夏路19號 | 武漢 | 430000 | 湖北省5 | 趙七 | 西二旗12號 | 北京 | 100000 | 北京市6 | 宋一 | 花城大道21號 | 廣州 | 510000 | 廣東省7 | 劉二 | 長安街 121 號 | 北京 | 100000 | 北京市8 | 宋江 | 梁山路1號 | 濟南 | 250000 | 山東省| 武松 | | 邢臺 | | 河北省10 | 韓信 | 梁山路1號 | 渝東 | 250001 | 四川省11 | 呂不韋 | 梁山路1號 | 渝中 | 250001 | 四川省
(11 rows)csdn=>
選自 "suppliers" 表的數據:
csdn=> select * from suppliers;id | name | addr | city | zip | province
----+----------+--------------+------+--------+----------1 | 沃爾瑪 | 北京路35號 | 上海 | 200000 | 上海市2 | 家樂福 | 玄武街28號 | 南京 | 210000 | 江蘇省3 | 永旺超市 | 花城大道21號 | 廣州 | 710000 | 廣東省4 | 宋江超市 | 梁山路1號 | 濟南 | 250000 | 山東省
(4 rows)csdn=>
6 union 舉證
以下 sql 語句從 "customers" 和"suppliers" 表中選擇所有不同的城市(只有不同的值):
select city from customers
union
select city from suppliers;
結果:
注:
7 union all 實例
以下 sql語句使用union all 從 "customers"和"suppliers" 表中選擇所有城市(也是重復的值):
select city as "城市" from customers
union all
select city from suppliers;
結果:
8 帶有 where 的 union all
以下 sql 語句使用 unionall 從"customers"和 "suppliers" 表中選擇所有上海市的城市(也是重復數值):
舉例:
select city as "城市", province as "省份" from customers
where province='廣東省'
union all
select city, province from suppliers
where province='廣東省';
結果:
9 帶有 where 的union
以下 sql 語句從"客戶"和"供應商"中選擇所有不同的上海城市(只有不同的值):
select city as "城市", province as "省份" from customers
where province='廣東省'
union
select city, province from suppliers
where province='廣東省';
結果:
10 批注
union 就是將多段功能類似的 sql 連接起來,并且可以去掉重復的行,有distinct 的功能。union all 則只是單純的將多段類似 sql 連接起來,而且他們的好處是可以將復雜 sql 按不同的功能或作用拆分成一小段 sql 進行拼接,可以有效提高查詢效率。