【问题标题】:SELECT count not working after added join [closed]添加加入后选择计数不起作用[关闭]
【发布时间】:2013-03-21 01:49:13
【问题描述】:

我有这个问题:

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 次,计数为 1。

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

【问题讨论】:

  • 。 .请显示返回您期望结果的查询。
  • 按关键字从关键字组中选择关键字,count(*)
  • 现在我添加了连接,只显示带有图片的引号的关键字。
  • 我认为该组不起作用,因为它显示每个关键字的次数更多。对于应具有 TotalTags=5 的关键字,它会显示关键字 5 次,计数为 1
  • @MarioM 请显示表结构和所需结果

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


【解决方案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 的单独结果。

【讨论】:

    【解决方案2】:

    您已经在分组中添加了一个额外的列,因此如果您有 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 列表?你为什么要把它介绍到这两个列表中?

    【讨论】:

    • Msg 208,级别 16,状态 1,第 2 行无效的对象名称“dbo.Keywords”。
    • @MarioM 好吧,您告诉我们表名。您是否尝试从正确的数据库 ([QuotesTemple]) 运行此查询?否则请自行添加数据库前缀。
    • 是的,您的第二个解决方案有效,但与我选择作为答案的查询相比要慢得多。这个查询用了 1 秒,另一个用了 0.1 秒,因为这有 2 次选择
    • 对不起,我不知道你所说的“这有 2 次选择”是什么意思...
    • 您在另一个选择中有一个选择,这很耗时
    【解决方案3】:

    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。每个报价都有一个标签。

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

    【讨论】:

    • 有些标签的关键词比较多,所以所有结果都不应该是1。
    • 与左外连接我得到了我不需要的反向结果,并且计数仍然是 1
    猜你喜欢
    • 2018-07-25
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 2013-12-26
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多