MySQL左连接使用SUM和Where子句返回Null

时间:2014-02-28 11:43:30

标签: mysql

我的查询存在问题,

SELECT id, name, cc, total FROM goods gd 
LEFT JOIN (SELECT count(*) as cc, status, pid, SUM(number) as total FROM prices)pr 
ON pr.pid = gd.id AND pr.status = 0 WHERE gd.id=20

当我在本地服务器上运行此查询时,如果正确获取但在我的远程服务器上,cc和total将返回null。

请问有关原因吗? 注意:如果我删除了count(*)和SUM(number)它会返回多行,我希望Left join能够在第二个表中获得总匹配和数字总和。

2 个答案:

答案 0 :(得分:1)

以下是您的查询:

SELECT id, name, cc, total
FROM goods gd LEFT JOIN
     (SELECT count(*) as cc, status, pid, SUM(number) as total
      FROM prices
     ) pr 
     ON pr.pid = gd.id AND pr.status = 0
WHERE gd.id=20;

子查询使用MySQL(mis)功能,允许您在select中包含pid中不在group by且不在聚合列中的列。 MySQL documentation非常清楚,这些列的值来自任意匹配记录,只有当列的所有值在组中相同时才应使用此功能。

正在发生的事情是服务器上的任意列的值为20.巧合的是,在本地服务器上,它确实如此。

您也遇到status问题,因此逻辑也不应该稳定。

你想要status = 0这样的总和吗?

SELECT gd.id, gd.name, pr.cc, pr.total
FROM goods gd LEFT JOIN
     (SELECT count(*) as cc, status, pid, SUM(number) as total
      FROM prices
      WHERE status = 0
      GROUP BY pid
     ) pr 
     ON pr.pid = gd.id
WHERE gd.id = 20;

或者,您是否只想匹配status始终等于0的记录?

SELECT gd.id, gd.name, pr.cc, pr.total
FROM goods gd LEFT JOIN
     (SELECT count(*) as cc, status, pid, SUM(number) as total
      FROM prices
      GROUP BY pid
      HAVING min(status) = 0 and max(status) = 0
     ) pr 
     ON pr.pid = gd.id
WHERE gd.id = 20;

答案 1 :(得分:0)

您必须在已加入的查询中添加group by pid

SELECT id, name, cc, total FROM goods gd 
LEFT JOIN (SELECT count(*) as cc, status, pid, SUM(number) as total 
           FROM prices group by pid)pr 
ON pr.pid = gd.id AND pr.status = 0 
WHERE gd.id=20