将记录限制在自连接查询中连接的一侧
考虑一个表(名称 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,并且有多个术语属于类别 1 或类别 2。我试图在这两个类别中或在这两个类别的单个类别中查找具有相同 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 不同,则不需要倒序结果。那么,我该如何一次性得到结果呢?
感谢您的帮助,
Consider a table (name Term) as follows:
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NOT NULL,
[Label] [nvarchar](256) NOT NULL,
[Uri] [nvarchar](1024) NOT NULL
Now, consider that there are two categories defined: CategoryId 1 and CategoryId 2 and there are multiple terms that belong either to category1 or category2. I'm trying to find those Terms that have the same URI but different labels in these two categories, or within a single category of those two. To do so, I tried to write a self join 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
This works fine, but each row is returned twice... For example,
TermId1, TermId2
TermId2, TermId1
If the termId1 is different from termId2, then there's no need to have the reverse order result. So, how am I supposed to get results once?
Thank you for your help,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下。您可能不需要分组依据
Give this a try. You may not need the group by