sql多个连接和计数

时间:2012-07-12 12:41:36

标签: mysql join count

我有这样的桌子。但似乎MySQL目前不计入我的第二次加入。我想知道我的评论列表的报告流程数我错过了什么。

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

好文章 2 报告。

count(report.id)给我错误的价值。我的错是什么?

2 个答案:

答案 0 :(得分: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

以下是示例:

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

答案 1 :(得分: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