为什么select语句从存在重复结果的表中返回不同的值?

时间:2015-07-29 08:47:04

标签: sql sql-server

我在这样的表中插入值(SQL Server)

create table #t1 (id int)

insert into #t1(id)
   select 1 union
   select 2 union
   select 2 union
   select 1 

select * from #t1

但它给了我这个数据:

  id
-----
  1
  2

虽然我需要以下数据:

  id
----
  1
  2
  2
  1

2 个答案:

答案 0 :(得分:3)

使用union all代替unionunion all允许选择冗余数据:

create table #t1 (id int)

insert into #t1(id)
select 1 union all
select 2 union all
select 2 union all
select 1 

答案 1 :(得分:1)

我只是回答其他thread

UNION始终返回不同的行,否则请使用UNION ALL