从匹配ID的不同表中获取总行数

时间:2009-05-22 16:42:00

标签: sql join

对于我的第一张桌子,我有这样的问题:

qid  | question | date
 1      blah      22-05-2009

然后我有表评论

cid | qid
 1     1
 2     1 
 3     1

然后在我的问题表中,我可以添加一个包含total_comments的列,其中包含三个

我尝试过使用此代码

SELECT
questions.qid,
questions.question,
questions.date,
sum(comments.qid) AS total_money
FROM
questions
INNER JOIN comments ON comments.qid = questions.qid
ORDER BY questions.date
LIMIT 1

但它有错误,只有当有一个日期更长的行时才抓住第一行?提前致谢

4 个答案:

答案 0 :(得分:1)

尝试:

;WITH comment_summary AS (
    SELECT comments.qid
        ,COUNT(*) AS comment_count
    FROM comments
    GROUP BY comments.qid
)
SELECT questions.qid
    ,questions.question
    ,questions.date
    ,ISNULL(comment_summary.comment_count, 0) AS comment_count
FROM questions
LEFT JOIN comment_summary
    ON comment_summary.qid = questions.qid
ORDER BY questions.date

或者,如果您的SQL方言不支持CTE:

SELECT questions.qid
    ,questions.question
    ,questions.date
    ,ISNULL(comment_summary.comment_count, 0) AS comment_count
FROM questions
LEFT JOIN (
    SELECT comments.qid
        ,COUNT(*) AS comment_count
    FROM comments
    GROUP BY comments.qid
) AS comment_summary
    ON comment_summary.qid = questions.qid
ORDER BY questions.date

答案 1 :(得分:0)

  SELECT COUNT(qid), qid
    FROM comments
    GROUP BY qid

将显示每个qid的评论数量 如果你想要一个特定的qid计数,它将是:

SELECT COUNT(qid)
FROM comments
WHERE qid = 1

答案 2 :(得分:0)

您需要在“ORDER BY”之前的语句中加入“GROUP BY questions.qid,questions.question,questions.date”。

答案 3 :(得分:0)

如果我理解正确,我想你想要:

SELECT questions.qid, question, date, SUM(comments.qid) 
FROM Questions 
LEFT OUTER JOIN Comments ON Questions.qid = Comments.qid
GROUP BY Questions.qid, Question, Date
ORDER BY Questions.Date