如何获取列的Sum和Group按Mysql中的行的唯一ID?

时间:2014-01-21 12:21:50

标签: mysql

这是我目前正在使用的查询,但我没有得到    预期产出。

SELECT u.user_id, u.email, SUM(ca.credits_added) as credits_added, SUM(cs.credits_spent) as credits_spent 
FROM weg_whitehound.users u
JOIN weg_whitehound.credits_added ca
ON u.user_id = ca.user_id
JOIN weg_whitehound.credits_spent cs
ON u.user_id = cs.user_id
GROUP BY ca.user_id

我的原始数据库是here

1 个答案:

答案 0 :(得分:0)

由于加入,您将获得所有可能的信用组合和为每个用户花费的信用。

您可能需要加入子查询: -

SELECT u.user_id, u.email, ca.credits_added, cs.credits_spent
FROM weg_whitehound.users u
JOIN (SELECT user_id, SUM(credits_added) as credits_added FROM weg_whitehound.credits_added GROUP BY user_id) ca
ON u.user_id = ca.user_id
JOIN (SELECT user_id, SUM(credits_spent) as credits_added FROM weg_whitehound.credits_spent GROUP BY user_id) cs
ON u.user_id = cs.user_id
GROUP BY u.user_id, u.email