INNER JOIN返回太多结果

时间:2010-03-27 22:16:12

标签: sql sql-server 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

而不只是两个记录,这些名称是“家”和“汽车”。我该如何解决?

感谢。

4 个答案:

答案 0 :(得分:3)

这是因为您告诉查询返回每一列,因此SQL将返回每个匹配的行。因此,您需要将查询更改为仅返回所需的列并添加DISTINCT子句(即SELECT DISTINCT)。

如果您提供所需输出的示例,我们可能会提供更有用的答案......

答案 1 :(得分:2)

有两种选择 - 使用JOIN:

SELECT *
  FROM [Database].dbo.[TagsPerItem] tpi
  JOIN [Database].dbo.[Tag] t_home ON t_home.id = tpi.tagid
                                  AND t_home.name = 'home'
  JOIN [Database].dbo.[Tag] t_car ON t_car.id = tpi.tagid
                                 AND t_car.name = 'car'

...或HAVING COUNT(DISTINCT t.name) = 2

  SELECT --column list - fill with specific appropriate columns
    FROM [Database].dbo.[TagsPerItem] tpi
    JOIN [Database].dbo.[Tag] t ON t.id = tpi.tagid
                               AND t.name IN ('home', 'car')
GROUP BY --column list - match columns declarations with the SELECT list without aggregates used on them
  HAVING COUNT(DISTINCT t.name) = 2
  • COUNT(DISTINCT是必要的,否则“car”的两个关系将是误报(假设在数据模型中可能)
  • 并非所有数据库都支持COUNT(DISTINCT...);虽然构造繁琐,但多次加入同一个表是一种更安全的方法

答案 2 :(得分:0)

SELECT DISTINCT Tag.Id, Tag.Name
FROM [Database].dbo.[TagsPerItem] 
INNER JOIN [Database].dbo.[Tag] ON [Tag].Id = [TagsPerItem].TagId 
WHERE [Tag].Name IN ('home', 'car') 

答案 3 :(得分:0)

SELECT * 
  FROM [Database].dbo.[TagsPerItem] tpi_car
  JOIN [Database].dbo.[TagsPerItem] tpi_home on tpi_home.ItemId = tpi_car.ItemId AND tpi_home. ItemTable  = tpi_car. ItemTable 
  JOIN [Database].dbo.[Tag] t_home ON t_home.id = tpi_home.tagid
                                  AND t_home.name = 'home'
  JOIN [Database].dbo.[Tag] t_car ON t_car.id = tpi_car.tagid
                                 AND t_car.name = 'car'