【问题标题】:Symmetric cross join对称交叉连接
【发布时间】:2012-09-19 18:38:49
【问题描述】:

我正在尝试从表中的每个元素中针对同一表中的每个元素提取所有对,例如 i,j,这是我的查询:

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

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    因此,只需设置连接条件,使左侧始终等于或小于!

        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,并且在join条件中不能使用等号。
    猜你喜欢
    • 2013-08-03
    • 2013-05-01
    • 1970-01-01
    • 2011-03-14
    • 2015-10-18
    • 1970-01-01
    • 2013-07-11
    • 2010-10-17
    • 2012-12-31
    相关资源
    最近更新 更多