在自联接查询中将记录限制到联接的一侧

时间:2011-09-28 15:54:15

标签: tsql sql-server-2008-r2 self-join

考虑一个表(名称Term)如下:

[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NOT NULL,
[Label] [nvarchar](256) NOT NULL,
[Uri] [nvarchar](1024) NOT NULL

现在,考虑定义了两个类别:CategoryId 1和CategoryId 2,并且有多个术语属于category1或category2。我试图找到那些在这两个类别中具有相同URI但标签不同的条款,或者在这两个类别的单个类别中。为此,我尝试编写自连接SQL:

SELECT
    t1.Id AS TermId1,
    t2.Id AS TermId2
FROM
    Term t1 INNER JOIN Term t2 ON t1.Uri = t2.Uri
WHERE
    t1.CategoryId IN (@CategoryId1, @CategoryId2) AND
    t2.CategoryId IN (@CategoryId1, @CategoryId2) AND
    t1.Label <> t2.Label

这样可以正常工作,但每行返回两次......例如,

TermId1,TermId2 TermId2,TermId1

如果termId1与termId2不同,则不需要具有相反的顺序结果。那么,我应该如何获得一次结果呢?

感谢您的帮助,

1 个答案:

答案 0 :(得分:1)

试一试。

你可能不需要这个小组
    SELECT t1.Id AS TermId1, t2.Id AS TermId2
    FROM
        Term t1 
        INNER JOIN Term t2 
          ON t1.Uri = t2.Uri
         AND t1.Label <> t2.Label
         AND t1.Id < t2.Id      
    WHERE
            t1.CategoryId IN (@CategoryId1, @CategoryId2) 
        and t2.CategoryId IN (@CategoryId1, @CategoryId2)          
    group by t1.Id, t2.Id
    order by t1.Id, t2.Id