在相关表中获取SUM。如果没有找到,则获得0作为总和

时间:2016-12-22 19:37:05

标签: php mysql sql

我有这个问题:

$sql = "SELECT m.id FROM members m
          LEFT JOIN orders o ON o.user_id = m.id AND
            YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND
            MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
          LEFT JOIN transactions t ON t.user_id = o.user_id";

我需要得到Transactions.points的总和,所以我这样做:

$sql = "SELECT m.id, COALESCE(SUM(t.points), 0) AS total_points FROM members m
          LEFT JOIN orders o ON o.user_id = m.id AND
            YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND
            MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
          LEFT JOIN transactions t ON t.user_id = o.user_id";

但是当我执行此操作时,我将只获得包含一些事务(和订单)的行。如果没有找到交易,我必须做什么才能获得0作为total_points?

文字说明:我想得到订单(订单表)的积分奖励(来自交易表),订单是在上个月创建的。

谢谢!

2 个答案:

答案 0 :(得分:1)

获取每位用户的积分总和,并在left join中使用该积分,以便在用户没有交易时获取0

SELECT m.id, COALESCE(t.total_points, 0) AS total_points
FROM members m
LEFT JOIN orders o ON o.user_id = m.id AND
/* use this instead of functions which prevent indexes on the date column from being used */
o.date >= date '2016-11-01' AND o.date <= date '2016-11-30' 
LEFT JOIN (select user_id, SUM(points) total_points 
           from transactions group by user_id) t ON t.user_id = o.user_id

答案 1 :(得分:0)

您需要在查询中添加items.forEach(addItemId) 子句,否则您在整个结果集上实际执行GROUP BY。不知道在哪个列上,但在SUM()

上说
m.id