I suspect your problem is the use of count()
rather than count(distinct)
. I think this is what you want:
SELECT ar_teams.*,
COALESCE(SUM(ar_points.amount), 0) AS points,
COUNT(distinct ar_users.id) AS members
質問
I have teams, users, and points tables.
When I call get the teams from the database I need to also calculate the points as a generated column and also the number of users in that team as a new column.
I have this so far but it is returning all users in the member count column, not just the members in that team.
SELECT ar_teams.*, COALESCE(SUM(ar_points.amount),0) AS points, COUNT(ar_users.team_id) AS members
FROM ar_teams
LEFT JOIN ar_users ON ar_users.team_id = ar_teams.id
LEFT JOIN ar_points ON ar_points.user_id = ar_users.id
WHERE ar_teams.id = 1 AND ar_users.team_id = 1
GROUP BY ar_teams.id
The results I am getting:
id name name_alt points members
1 UK & Ireland NULL 3076 48
The members count should be 12, at the moment it seems to be counting all people without taking their team into account.
解決
I suspect your problem is the use of count()
rather than count(distinct)
. I think this is what you want:
SELECT ar_teams.*,
COALESCE(SUM(ar_points.amount), 0) AS points,
COUNT(distinct ar_users.id) AS members