0

我有 2 张桌子:

users:
id   |  name   |  club_id |
1       Bob         4
2       Jane        5
3       Alex        4 
4       Paul        4
5       Tom         4

points:
user_id    |   club_id    |   amount(can vary)
1                 4             10
1                 2             10
2                 5             10
3                 4             10
3                 4             10
4                 4             10
3                 2             10
3                 4             10

I need (where users.club_id = 4 AND points.club_id = 4):
user_id    |    name    |   sum(amount)
3             Alex           30
1             Bob            10
4             Paul           10
5             Tom             0      

请注意,Tom 存在于用户中,但没有任何积分条目,因此他的总和应该为 0。这就是让我从用户那里获取列表的原因。

也希望这尽可能高效(因此我在用户和积分中都添加了 club_id = 4)

4

2 回答 2

3

尝试这个:

SELECT
  u.id,
  u.name,
  COALESCE(SUM(p.amount), 0) AS Totalpoints
FROM
(
  SELECT * 
  FROM users
  WHERE club_id = 4
) AS u
LEFT JOIN
(
  SELECT * 
  FROM points
  WHERE club_id = 4
) AS p ON p.user_id = u.id 
GROUP BY u.id, 
         u.name;

在这里查看它的实际效果:

于 2013-05-21T10:25:10.550 回答
2

试试这个查询

select u.id, u.name, sum(if (p.amount is null, 0, p.amount)) as totalPoint
from 
user u 
left join 
(select * from point p where p.club_id = 4)p
on u.id = p.user_id
where u.club_id=4 
group by u.id

SQL 小提琴

于 2013-05-21T10:32:25.607 回答