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_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主要注意两点

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

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值