2009-05-22 5 views
0

Für meine erste Tabelle habe ich Fragen wie diese:Setzen Sie sich mit ID passenden

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

und dann habe ich die Tabelle kommentiert

cid | qid 
1  1 
2  1 
3  1 

so dann in meinen Fragen Tabelle konnte ich eine zusätzliche Spalte, die total_comments hatte die drei

Ive würde tryed diesem 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 

aber es Fehler und nur die erste Zeile ergreift, wenn es eine Zeile mit einem größeren Datum gibt? Vielen Dank im Voraus

Antwort

0

Wenn ich richtig verstehe, ich glaube, Sie wollen:

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 
+0

diese funktioniert ein wenig, es scheint, dass es die richtigen Ergebnisse für QID 1 erhält, aber wenn es QID 2 eine falsche Menge ausarbeitet, gibt es nur 2 Zeilen für QID 2, aber seine com zurück als 6, als ob es die Ergebnisse durch sein Selbst multipliziert? –

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

Zeigt Ihnen die Anzahl der Kommentare pro qid.
Wenn Sie eine bestimmte qid Zählung wollen, wäre es:

SELECT COUNT(qid) 
FROM comments 
WHERE qid = 1 
0

Sie müssen "GROUP BY questions.qid, questions.question, questions.date" in Ihrer Erklärung vor dem "BY ORDER" haben.

1

Versuchen:

;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 

Oder, wenn Ihr SQL-Dialekt, nicht unterstützt 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