SQL Server联合结果集(union)



  union操作符用于合并另个或多个select(查询)语句的结果集。   在使用union操作符时,要注意联合的select语句需要有相同的列、相似的数据类型、列的顺序要相同。

union和union all

union默认去掉合并结果中重复的数据。 ★ union all可以保留重复的结果数据。

语法

1
2
3
select * from table1_name
union|union all
select * from table2_name

union结果集中的列名总是等于第一条select语句的列名

代码示例

union示例:

1
2
3
select Name from Staff
union
select name from Staff2

union all示例:

1
2
3
select Name from Staff
union all
select name from Staff2