简体   繁体   English

SUM 在 MYSQL 查询中与 LEFT JOIN 和 GROUP BY 混合

[英]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我在涉及 sum、left join 和 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.如果没有喜欢,它会给出 NULL 或数字 8873,如果它有一个,它会给出 NULL ,而不是对每个家庭的喜欢求和。 I really can't understand the 8873.实在看不懂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.值得注意的是,在此表中还有很多其他事物的赞,在这种情况下,l.homeid 的值为 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.我为来自不同用户的 homeid 添加了另一个赞,现在它给我 8906 而不是 8873 给那些有 1 个赞的人和 17812 给有两个赞的人。 This is very strange.这很奇怪。 The data type for all the numbers is int(11).所有数字的数据类型都是 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()也尝试COUNT()而不是SUM()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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