INNER JOIN 返回太多结果
我有以下 SQL:
SELECT *
FROM [Database].dbo.[TagsPerItem]
INNER JOIN [Database].dbo.[Tag] ON [Tag].Id = [TagsPerItem].TagId
WHERE [Tag].Name IN ('home', 'car')
它返回:
Id TagId ItemId ItemTable Id Name SiteId
------------------------------------------
1 1 1 Content 1 home 1
2 1 2 Content 1 home 1
3 1 3 Content 1 home 1
4 2 4 Content 2 car 1
5 2 5 Content 2 car 1
6 2 12 Content 2 car 1
而不是只有两条记录,这些记录的名称是“home”和“car”。我该如何修复它?
谢谢。
I have the following SQL:
SELECT *
FROM [Database].dbo.[TagsPerItem]
INNER JOIN [Database].dbo.[Tag] ON [Tag].Id = [TagsPerItem].TagId
WHERE [Tag].Name IN ('home', 'car')
and it returns:
Id TagId ItemId ItemTable Id Name SiteId
------------------------------------------
1 1 1 Content 1 home 1
2 1 2 Content 1 home 1
3 1 3 Content 1 home 1
4 2 4 Content 2 car 1
5 2 5 Content 2 car 1
6 2 12 Content 2 car 1
instead of just two records, which these names are "home" and "car". How can I fix it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为您告诉查询返回每一列,因此 SQL 将返回每个匹配的行。因此,您需要将查询更改为仅返回所需的列,并添加 DISTINCT 子句(即 SELECT DISTINCT )。
如果您提供所需输出的示例,我们也许能够提供更有用的答案......
It's because you're telling the query to return every column, so SQL will return every matching row. So you'll need to change the query to only return the columns you need and add a DISTINCT clause (i.e.
SELECT DISTINCT
).If you provide an example of the output you want, we might be able to provide a more useful answer...
有两种替代方案 - 使用 JOIN:
...或
HAVING COUNT(DISTINCT t.name) = 2
:COUNT(DISTINCT
) 是必要的,否则“car”的两个关系" 将是误报(假设在数据模型中可能)COUNT(DISTINCT...)
;虽然构建起来很繁琐,但多次 JOIN 到同一个表是一种更安全的方法There are two alternatives - using JOINs:
...or
HAVING COUNT(DISTINCT t.name) = 2
:COUNT(DISTINCT
is necessary, otherwise two relations of "car" would be a false positive (assuming possible in the data model)COUNT(DISTINCT...)
; while tedious to construct, JOINing to the same table multiple times is a safer method