对称交叉连接

5

我正在尝试从表中的每个元素对每个相同表上的元素提取所有配对,这是我的查询:

select a.Id L,b.id R into #cross from MyTable a cross join mytable b 

我处于这样一种情况: i,j == j,i,因此只需要记录一半的数据。我的初步尝试如下:
select a.Id L,b.id R into #cross from MyTable a cross join mytable b 
where not exists
    (select * from #cross c where c.L=R and c.R=L)

但是根据SQL Server的说法,我无法在插入时查询目标表:

The SELECT INTO statement cannot have same source and destination tables

我应该如何高效完成这个任务?

编辑 仅供参考,我说了“我需要一半的记录”,这是错误的,考虑到i,j == j,i,记录数应为n *(n + 1)/ 2

1个回答

8
因此,只需将连接条件设置为左侧始终小于或等于右侧即可!
    select a.Id L,b.id R
      into #cross
      from MyTable a
inner join mytable b on a.id <= b.id

为了获得正确的结果,a.id 应该小于 b.id,并且在连接条件中不应使用等号。 - QMaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接