如何使用WHERE子句对两个子查询求和

时间:2017-05-02 14:43:57

标签: mysql

我有这个问题:

offline_access

但是我收到了这个错误:

SELECT *,
COALESCE((
    SELECT SUM(sum_points)
    FROM (
        SELECT SUM(user_points.points) AS sum_points FROM user_points
        WHERE user_points.user_id = user.user_id
        UNION ALL
        SELECT SUM(used_points.points) AS sum_points FROM used_points
        WHERE used_points.user_id = user.user_id
    ) t
), 0) AS total_points_credit
FROM user

如何在子查询的WHERE条件中使用user.user_id值?

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为您不需要拥有所有这些子查询。我觉得你可能会做你想做的事情:

SELECT A.user_id, SUM(B.points) + SUM(C.points) total_points_credit FROM user A
JOIN user_points B ON
    A.user_id = B.user_id
JOIN used_points C ON
    A.user_id = C.user_id

GROUP BY A.user_id

答案 1 :(得分:0)

尝试这种方式:

SELECT *,
       COALESCE((SELECT SUM(user_points.points) 
                 FROM user_points
                 WHERE user_points.user_id = user.user_id), 0)
        +
        COALESCE((SELECT SUM(used_points.points)  
                  FROM used_points
                  WHERE used_points.user_id = user.user_id), 0) AS total_points_credit
FROM user