MYSQL SUM和减法

时间:2012-07-05 13:55:36

标签: mysql sum

我有以下SQL查询。

SELECT    u.username, SUM(p.points) AS points,
          SUM(sp.spPoints) AS spPoints,
          (SUM(sp.spPoints) - SUM(p.points)) AS Puntos_Restantes
FROM      users as u
LEFT JOIN points as p ON (u.userid = p.userid)
LEFT JOIN sppoints AS sp ON (u.userid = sp.userid)
WHERE     u.userid = '1'
GROUP BY  u.userid

我的目标是SUM 2字段然后减去它们但是当我执行上面的查询时,第二个SUM是错误的。
表格如下:

points: pointId, userId, points    
sppoints: spPointId, userId, spPoints    

在点上我有这个数量:25和spPoints:10 但当我运行查询时,我得到:

points  spPoints    Puntos_Restantes
 25       30              5

这里出了什么问题?

1 个答案:

答案 0 :(得分:3)

users与其他两个表都有一对多的关系。这会导致2个连接生成一个mini-Carstesian产品,并在points列中生成具有相同数据的多个行 - 然后进行聚合。

您可以使用子查询进行分组,然后加入,以避免此问题:

SELECT 
      u.username
    , COALESCE(p.pPoints,0) 
        AS pPoints
    , COALESCE(sp.spPoints,0) 
        AS spPoints
    , COALESCE(p.pPoints,0) - COALESCE(sp.spPoints,0)
        AS Puntos_Restantes
FROM 
      users as u
  LEFT JOIN 
      ( SELECT userid, SUM(points) AS pPoints
        FROM points
        WHERE userid = 1
        GROUP BY userid
      ) AS p
    ON u.userid = p.userid
  LEFT JOIN 
      ( SELECT userid, SUM(spPoints) AS spPoints
        FROM sppoints
        WHERE userid = 1
        GROUP BY userid
      ) AS sp
    ON u.userid = sp.userid
WHERE u.userid = 1 ;

如果您希望为多个用户(或所有用户)提供结果,请替换三个WHERE userid=1条件(或完全删除它们)。

points(userid, points)sppoints(userid, spPoints)上的指标有助于提高效率。