SQL Union和SQL Union All用法
SQL Union
UNION 指令的目的是将两个 SQL 语句的结果合并起来。从这个角度来看, UNION 跟 JOIN 有些许类似,因为这两个指令都可以由多个表格中撷取资料。 UNION 的一个限制是两个 SQL 语句所产生的栏位需要是同样的资料种类。另外,当我们用 UNION这个指令时,我们只会看到不同的资料值 (类似 Select DISTINCT)。 union只是将两个结果联结起来一起显示,并不是联结两个表………… UNION 的语法如下: [SQL 语句 1]
UNION
SQL Union All
UNION ALL 这个指令的目的也是要将两个 SQL 语句的结果合并在一起。 UNION ALL 和 UNION 不同之处在于 UNION ALL 会将每一笔符合条件的资料都列出来,无论资料值有无重复。 UNION ALL 的语法如下: [SQL 语句 1]
UNION ALL
[SQL 语句 2]
实例(可以直接在查询分析器里查询并看到对比结果):
declare @t table
(
a int ,
b int
)
declare @s table
(
a int,
b int
)
insert into @t select 1,1
insert into @t select 1,2
insert into @s select 1,1
insert into @s select 1,3
select * from @t
union
select * from @s
select * from @t
union all
select * from @s