我有3张桌子:
我想选择每个用户的总收益与总支出之差。所以我的假设表可能是:
我尝试过:
SELECT g.total - s.total AS quantity, id FROM
(SELECT SUM(quantity) AS total FROM gain GROUP BY user) AS g,
(SELECT SUM(quantity) AS total FROM spent GROUP BY user) AS s, users
但这不起作用...
答案 0 :(得分:1)
您需要使用users
表作为基本表,以便能够考虑所有用户,然后LEFT JOIN
到子查询中计算总支出和总收益。这是因为某些用户在收益表或消费表中可能没有任何条目。另外,Coalesce()
函数处理NULL
(如果没有匹配的行)
SELECT
u.id AS user,
COALESCE(tot_gain, 0) - COALESCE(tot_spent, 0) AS balance
FROM users AS u
LEFT JOIN (SELECT user, SUM(quantity) as tot_spent
FROM spent
GROUP BY user) AS s ON s.user = u.id
LEFT JOIN (SELECT user, SUM(quantity) as tot_gain
FROM gain
GROUP BY user) AS g ON g.user = u.id
答案 1 :(得分:0)
Madhur的解决方案很好。另一种选择是union all
和group by
:
select user, sum(gain) as gain, sum(spent) as spent
from ((select user, quantity as gain, 0 as spent
from gain
) union all
(select user, 0, quantity as spent
from spent
)
) u
group by user;
如果您希望不在表中的用户或需要其他列的用户,可以从join
到user
。但是,join
可能不是必需的。