简体   繁体   中英

sql query - wrong result

I have two tables, one of them contains comments and the other the rating for each comment. Here`s the query:

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;

Tables content:

table Comments:
id
40
41
42

table Rating:
comment_id  Rating
41            -1
42             1

The query should return:

id     Rating
41       -1
42        1
43        0

REturns:

id     Rating
41        2

Could you please somebody tell me where`s the mistake.

Can you try the below version?

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;

Why do you use COUNT here?

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

It should probably be

IFNULL(r.rate, 0) AS rate

Your final query would be like:

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;

However - you don't need a subquery. You can get the same result with

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

Demo: http://rextester.com/UIK19423

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM