select 中的union 和union all用法
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type.
Note: With UNION, only distinct values are selected.
SQL Statement 1 UNION SQL Statement 2 |
Employees_Norway
E_ID | E_Name |
---|---|
01 | Hansen, Ola |
02 | Svendson, Tove |
03 | Svendson, Stephen |
04 | Pettersen, Kari |
Employees_USA:
E_ID | E_Name |
---|---|
01 | Turner, Sally |
02 | Kent, Clark |
03 | Svendson, Stephen |
04 | Scott, Stephen |
Using the UNION Command
Example
List all different employee names in Norway and USA:
SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA |
Result
E_Name |
---|
Hansen, Ola |
Svendson, Tove |
Svendson, Stephen |
Pettersen, Kari |
Turner, Sally |
Kent, Clark |
Scott, Stephen |
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them is listed. The UNION command only selects distinct values.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
SQL Statement 1 UNION ALL SQL Statement 2 |
Using the UNION ALL Command
Example
List all employees in Norway and USA:
SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA |
Result
E_Name |
---|
Hansen, Ola |
Svendson, Tove |
Svendson, Stephen |
Pettersen, Kari |
Turner, Sally |
Kent, Clark |
Svendson, Stephen |
Scott, Stephen |
上面這個範例很好的描述了union的用法,對於union主要注意兩點
union(或union all)兩邊的結果集的列數必須一致,相同位置的列型別必須一致
例如 select t1.column1,t1.column2...t1.columnX from testtable1 t1
union
select t2.column1,t2.column2...t2.columnX from testtable2 t2
select 後所跟的column數必須一致
t1.column1 與 t2.column1的型別必須一致
但是t1.column1與 t2.column1的名字可以不一致
即t1.column1的名字可以是 aaa
t2.column1的名字可以是 ccc,
隨便什麼都可以
另外一個就是 union(或union all)
union:如果查詢出來的結果中有重複記錄,那麼就去重 ,從範例中有明顯表現,英文稱之為"distinct"
union all:就顯示所有的符合條件的記錄,重複也保留