【问题标题】:SQL SERVER Join 2 tables with COUNT(*)SQL SERVER 使用 COUNT(*) 连接 2 个表
【发布时间】:2014-07-05 21:24:15
【问题描述】:

我需要一些帮助来加入我的表格,我使用了 2 个表格

//餐桌新闻

id_news|title|
1 |first..|
2 |second..|

//表格注释

id_comment|content|id_news
1|Haha..|1
2|Hahe..|2
3|Hoho..|1

我需要在 id_news 1 中使用COUNT(*) cmets 输出

喜欢

id_news|title|total_comment|
1|first..|**2**|

到目前为止我的语法像

SELECT
    news.id_news,
    COUNT(distinct comment.id_news)
FROM
    news 
    inner join comment ON (comment.id_news=news.id_news)
group by 
    news.id_news

【问题讨论】:

  • 您的语法使用了不在表中的列名。请修复代码,使其与定义匹配。
  • 抱歉,我已经解决了我的问题
  • 只按第一列news.id_news(而不是神秘和无关的news.id_berita)分组并简单地使用count(*)
  • 我的问题终于解决了

标签: sql database sql-server-2008 join inner-join


【解决方案1】:

我想你想要:

SELECT news.id_news, COUNT(*)
FROM news INNER JOIN
     comment
     ON comment.id_news = news.id_news
GROUP BY news.id_news;

注意以下几点:

  • select 子句使用与group by 相同的列
  • COUNT() 未使用 distinct。在您的公式中,它总是返回 1,无论 cmets 的数量是多少。
  • 如果您想要没有 cmets 的新闻项目,您可以使用 left outer join 并将 count(*) 更改为 count(comment.id_news)

【讨论】:

    【解决方案2】:

    试试这个查询,你会得到你想要的数据:

    SELECT
        news.id_news,news.title,
        (select count(*) from comment group_by id_news) as total_comment
    FROM
        news 
        inner join comment ON comment.id_news=news.id_news
    

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多