0

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

在此处输入图像描述

我希望平均费率也计算报告

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)给我错误的价值。我的错误是什么?

4

2 回答 2

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

于 2012-07-12T13:44:17.370 回答
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 
于 2012-07-12T12:46:35.223 回答