添加连接后SELECT计数不起作用

时间:2013-03-30 13:06:15

标签: sql sql-server-2008 select join count

我有这个问题:

select Keyword, Keywords.QuoteId, count(*) AS TotalTags 
from [QuotesTemple].[dbo].Keywords 
join [QuotesTemple].[dbo].QuoteImages 
ON QuoteImages.QuoteId=Keywords.QuoteId
group by Keyword, Keywords.QuoteId

除了TotalTags始终为1之外,查询才有效,在我添加其工作的连接之前。

对于应具有TotalTags = 5的关键字,它会将计数器显示关键字5次。

如果从组中删除Keywords.QuoteId,查询将返回错误。

4 个答案:

答案 0 :(得分:1)

这有用吗?

select Keyword, count(QuoteImages.QuoteId) AS TotalTags 
from [QuotesTemple].[dbo].Keywords 
join [QuotesTemple].[dbo].QuoteImages 
ON QuoteImages.QuoteId=Keywords.QuoteId
group by Keyword

正如@Nenad指出的那样,引起问题的可能就是QuoteId。您不希望为每个QuoteId看到单独的结果。

答案 1 :(得分:1)

您已在分组中添加了其他列,因此,如果您有任意关键字的5个唯一引号,则每个组合的计数当然为1.尝试:

select k.Keyword, k.QuoteId, 
  count(*) OVER (PARTITION BY k.Keyword) AS TotalTags 
from [enter_your_database_name_here].[dbo].Keywords AS k
INNER JOIN [enter_your_database_name_here].[dbo].QuoteImages AS q
ON k.QuoteId = q.QuoteId
group by k.Keyword, k.QuoteId;

如果您不希望每个QuoteId看到一行,请将其从SELECT列表和GROUP BY中取出。您可能也根本不关心联接,为什么不赌博可能获得稍微更好的性能(或者,最坏的情况下,相同):

SELECT k.Keyword, COUNT(*) AS TotalTags
FROM [enter_your_database_name_here_if_you_want_to
  run_from_another_database_for_some_reason].dbo.Keywords AS k
WHERE EXISTS
(
  SELECT 1 FROM [enter_your_database_name_here_if_you_want_to
  run_from_another_database_for_some_reason].dbo.QuoteImages
  WHERE QuoteID = k.QuoteID
)
GROUP BY k.Keyword;

如果您不关心个别行情,那么我不知道您为何添加。你说你有错误,但这是因为你只将它添加到SELECT列表或仅添加到GROUP BY列表?为什么要将它引入任何一个列表?

答案 2 :(得分:0)

join替换为left outer join时会发生什么:

select Keyword, Keywords.QuoteId, count(*) AS TotalTags 
from [QuotesTemple].[dbo].Keywords 
left outer join [QuotesTemple].[dbo].QuoteImages 
ON QuoteImages.QuoteId=Keywords.QuoteId
group by Keyword, Keywords.QuoteId

我能想到两件事。一个是您在添加联接时添加了keywords.QuoteId。并且每个引号都有一个标记。

另一个是只有部分关键字引用。

答案 3 :(得分:0)

试试这个

select Keyword, Keywords.QuoteId, count(Keywords.QuoteId) AS TotalTags 
from [QuotesTemple].[dbo].Keywords
join [QuotesTemple].[dbo].QuoteImages
ON QuoteImages.QuoteId=Keywords.QuoteId
group by Keyword, Keywords.QuoteId

这假设所有行都匹配连接,否则LEFT JOIN将需要返回NULL结果。正如戈登·林诺夫所说的那样。