tags:

views:

172

answers:

4

For my first table i have questions like this:

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

and then i have the table comments

cid | qid
 1     1
 2     1 
 3     1

so then in my questions table i could have an added column which had total_comments which would be three

Ive tryed 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 it errors and only grabs the first row when there is a row with a greater date? Thanks in advance

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

Will show you the number of comments per qid.
If you want a specific qid count, it would be:

SELECT COUNT(qid)
FROM comments
WHERE qid = 1
Nick
A: 

You need to have "GROUP BY questions.qid, questions.question, questions.date" in your statement before the "ORDER BY".

araqnid
A: 

If i understand correctly, I think you want:

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
dsrekab
this works a bit, it seems that its getting the correct results for QID 1 but when it works out QID 2 its a wrong amount, there are only 2 rows for QID 2 but its coming back as 6 as if its multiplying the results by its self?
+1  A: 

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
Cade Roux