2012-07-12 41 views
0

我有這樣的表。但它似乎MySQL不計算我目前的第二次連接。我想知道我錯過了我的評論列表的報告流程數。sql多個加入和計數

enter image description here

,我想擁有率平均也算報告

SELECT *, avg(rate.score), count(report.id) FROM `comment` 
left join rate on (comment.id = rate.comment_id) 
left join report on (comment.id = report.comment_id) 
group by comment.id 

id text   id  comment_id score id  comment_id type avg(rate.score)  count(report.comment_id) 
1 good article 1  1   2  1  1   1  4.0000    20 
2 bad article  NULL NULL  NULL NULL NULL  NULL NULL    0 

好文章有報告。

count(report.id)給我錯誤的值。我的錯誤是什麼?

+0

我看到'計數(report.id)',這是一個錯字嗎? – 2012-07-12 13:42:14

回答

1
SELECT 
    *, 
    avg(rate.score), 
    (SELECT 
      count(report.comment_id) 
     FROM 
      report 
     WHERE 
      comment.id = report.comment_id) AS num_reports 
FROM 
    comment 
     left join 
    rate ON (comment.id = rate.comment_id) 
group by comment.id 

這裏的例子:在您的查詢和`計數(report.comment_id)`在結果

http://sqlfiddle.com/#!2/cf313/15

0

你不需要*。試試這個

SELECT comment.id, avg(rate.score), count(report.id) FROM `comment` 
left join rate on (comment.id = rate.comment_id) 
left join report on (comment.id = report.comment_id) 
group by comment.id 
+0

不工作...相同的結果 – sweb 2012-07-12 13:03:58