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:就显示所有的符合条件的记录,重复也保留