想问一下,我用两张表做测试
表1,select id,content from #temp1
表2, select id,content from #temp2
然后我用union
select * from #temp1
union
select * from #temp2
这样的结果是我所要的
但是当我把
select * from #temp1,v_test where #temp1.id=v_test.id
union
select * from #temp2,v_test where #temp2.id=v_test.id
这样查询出来的数据就不会让select * from #temp2,v_test where #temp2.id=v_test.id的数据都显示在
select * from #temp1,v_test where #temp1.id=v_test.id下面会出现交叉,
这是为什么
表1,select id,content from #temp1
表2, select id,content from #temp2
然后我用union
select * from #temp1
union
select * from #temp2
这样的结果是我所要的
但是当我把
select * from #temp1,v_test where #temp1.id=v_test.id
union
select * from #temp2,v_test where #temp2.id=v_test.id
这样查询出来的数据就不会让select * from #temp2,v_test where #temp2.id=v_test.id的数据都显示在
select * from #temp1,v_test where #temp1.id=v_test.id下面会出现交叉,
这是为什么
select * from #temp2,v_test where #temp2.id=v_test.id
这是一个内连接
可以翻译成
select * from #temp2 inner join v_test where #temp2.id=v_test.id 内连接只返回满足条件的记录
Union
不会显示相同的记录
使用union all可以了
union会把两个表的内容合并,但是会取消重复的
insert into #t select 1 ,'a'
insert into #t select 2 ,'a'select name from #t where id=1
union all
select name from #t where id=2/*
a
a
*/
select name from #t where id=1
union
select name from #t where id=2
/*
a
*/
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