SQL为每个用户获取唯一ID

时间:2017-12-03 16:08:14

标签: mysql sql

如何通过user_id对语句进行分组,我一直在user_id上使用已经使用过组的2和3的重复项?什么似乎是错误?

SELECT user_id, SUM(amount) 
FROM users INNER JOIN
     user_privileges 
     ON users.id = user_privileges.user_id 
GROUP BY user_id, amount 
ORDER BY user_id;

+---------+-------------+
| user_id | SUM(amount) |
+---------+-------------+
|       1 |     3000.00 |
|       2 |     2500.00 |
|       2 |    19000.00 |
|       3 |     2500.00 |
|       3 |    19000.00 |
|       4 |    12000.00 |
+---------+-------------+

3 个答案:

答案 0 :(得分:4)

简单的答案是只按userid分组,而不是amount

SELECT user_id, SUM(amount)
FROM users INNER JOIN
     user_privileges 
     ON users.id = user_privileges.user_id
GROUP BY user_id
ORDER BY user_id;

然而,join似乎甚至没有必要。你可以这样做:

SELECT user_id, SUM(amount)
FROM user_privileges 
GROUP BY user_id
ORDER BY user_id;

答案 1 :(得分:1)

SELECT user_id, SUM(amount) FROM users 
INNER JOIN user_privileges 
ON users.id = user_privileges.user_id 
GROUP BY user_id 
ORDER BY user_id;

答案 2 :(得分:1)

SELECT distinct (user_id), SUM(amount) 
FROM users 
INNER JOIN user_privileges 
on users.id = user_privileges.user_id 
GROUP BY user_id, amount 
ORDER BY user_id;