Mysql SUM 0不在另一个表中时

时间:2013-05-21 10:21:02

标签: mysql sum

我有两张桌子:

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)

2 个答案:

答案 0 :(得分: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;

请在此处查看:

答案 1 :(得分: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 FIDDLE