# select 中的union 和union all用法

3 篇文章 0 订阅

### 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_IDE_Name
01Hansen, Ola
02Svendson, Tove
03Svendson, Stephen
04Pettersen, Kari

Employees_USA:

E_IDE_Name
01Turner, Sally
02Kent, Clark
03Svendson, Stephen
04Scott, 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 all)两边的结果集的列数必须一致，相同位置的列类型必须一致

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

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
08-26 7096
11-10 9384
12-12 2396
09-29 380
08-23 1356
01-14 1407

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。