SQL查询 - 错误的结果

时间:2017-04-05 14:58:31

标签: mysql

我有两个表,其中一个包含注释,另一个包含每个注释的评级。 这是查询:

SELECT c.id,
       c.parent_id,
       c.name,
       c.body AS comment,
       c.user_id, 
       DATE_FORMAT( c.date_add, '%d %M %Y %H:%i') AS dt,
       c.deleted, 
       IFNULL( SUM( r.rate ), 0 ) AS rate
FROM comments AS c
LEFT JOIN
(
    SELECT SUM(rating) AS rate, 
           comment_id AS comment_id
    FROM rating
    GROUP BY comment_id
) r ON c.id = r.comment_id;

表格内容:

table Comments:
id
40
41
42

table Rating:
comment_id  Rating
41            -1
42             1

查询应返回:

id     Rating
41       -1
42        1
43        0

REturns:

id     Rating
41        2

请问有人告诉我错误在哪里。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下版本吗?

SELECT c.id, 
       c.parent_id,
       c.name,
       c.body AS comment,
       c.user_id,
       DATE_FORMAT( c.date_add, '%d %M %Y %H:%i'),
       c.deleted,
       (SELECT SUM(rating) FROM rating r Where r.comment_id = c.id) AS rate
FROM comments AS c;

答案 1 :(得分:0)

为什么在这里使用COUNT

IFNULL( COUNT( r.rate ), 0 ) AS rate

应该是

IFNULL(r.rate, 0) AS rate

您的最终查询如下:

SELECT c.*,
       IFNULL(r.rate, 0) AS rate
FROM comments AS c
LEFT JOIN
(
    SELECT SUM(rating) AS rate, 
           comment_id AS comment_id
    FROM rating
    GROUP BY comment_id
) r ON c.id = r.comment_id;

但是 - 你不需要子查询。您可以使用

获得相同的结果
SELECT c.*,
       IFNULL(SUM(rating), 0) AS rate
FROM comments AS c
LEFT JOIN rating r ON c.id = r.comment_id
GROUP BY c.id

演示:http://rextester.com/UIK19423