在三个表上使用左连接的mysql和

时间:2013-08-28 16:00:01

标签: mysql

我们有以下表格......

users
id, username password email

user_clubs
id, user_id, club_name

sales
id, club_id, amount, admin_fees, dnt

我们试图将admin_fees的总和作为user_id的未完成(例如5),我们尝试了以下...

SELECT u.id, count(c.id), SUM(s.admin_fees) as total_admin_fees 
FROM users u
LEFT JOIN user_clubs c ON c.user_id = u.id
LEFT JOIN sales s ON s.club_id = c.id
WHERE u.id = 5
GROUP BY u.id;

哪一个只返回第一行的结果,这是不正确的,请帮忙解决。

这里是sql fiddle来测试。

感谢

1 个答案:

答案 0 :(得分:0)

user_id = 5尝试这个,有两个俱乐部ID,金额为2,5,所以总数应 7

SELECT u.id, COUNT(c.id), SUM(s.admin_fees) AS total_admin_fees 
FROM users u
LEFT JOIN user_clubs c ON c.user_id = u.id
LEFT JOIN sales s ON s.club_id = c.id
WHERE u.id = 5
GROUP BY s.club_id;

对于所有用户,您可以执行此操作

SELECT u.id, COUNT(c.id), SUM(s.admin_fees) AS total_admin_fees 
FROM users u
LEFT JOIN user_clubs c ON c.user_id = u.id
LEFT JOIN sales s ON s.club_id = c.id

GROUP BY u.`id`;

Fiddle