简体   繁体   中英

SUM mixed with LEFT JOIN and GROUP BY in MYSQL query

I am having some trouble with a query that involves sum, a left join and a group by

$sql = "
SELECT h.id AS hid
     , SUM(l.likes) AS likes 
  FROM homes h
  LEFT 
  JOIN likes l
    ON l.homeid = h.id
 GROUP 
    BY h.id
";

Instead of summing the likes for each home, it is giving NULL if the home has no likes or the number 8873 if it has one like. I really can't understand the 8873.

Of note, there are a lot of likes in this table for other things in which case the value for l.homeid is NULL. Could that be throwing things off?

Edit:

I added another like for a homeid from a different user and now it is giving me 8906 instead of 8873 for those with 1 like and 17812 for the one with two likes. This is very strange. The data type for all the numbers is int(11). I am going to create a totally new table and see if that one does the same thing. I'm also going to remove a unique index I added recently.

Try moving the aggregation into a derived table and joining then joining that:

SELECT
    h.id                   AS hid
  , COALESCE( l.likes, 0 ) AS likes
FROM homes h
LEFT JOIN (
        SELECT
            homeid
          , COUNT( likes ) AS likes
        FROM likes
        GROUP BY
            homeid
    ) AS l ON h.id = l.homeid

Also try COUNT() instead of SUM()

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