-3

我们有以下表格...

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 。

谢谢

4

1 回答 1

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`;

小提琴

于 2013-08-28T16:06:50.533 回答