Get total row count from another table with matching id
For my first table, I have questions like this:
qid | question | date
1 blah 22-05-2009
and then I have comments on the table
cid | qid
1 1
2 1
3 1
so in my question table I could have a column added that had total_comments which would be three
I tried using this code
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
but is it errors and only grabs the first row when there is a row with a higher date? thanks in advance
0
Johnnny
a source
to share
4 answers
Try:
;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
Or, if your SQL dialect doesn't support CTEs:
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
a source to share