Reputation: 271
I have a user_groups
table, a users
table and an orders
table.
The relationship between them is this: users.group_id
, orders.user_id
.
I'm trying to get the amount of users that belong to each group, and the amount of orders that belong to each group through its users.
My code:
select user_groups.*, count(users.id) as user_count, count(orders.id) as order_count
from user_groups
left join users on user_groups.id=users.group_id
left join orders on users.id=orders.user_id
group by user_groups.id
Expected output:
id | user_count | order_count
1 | 5 | 67
2 | 1 | 1
Actual output:
The amount of orders should be 5, not 71:
Upvotes: 0
Views: 28
Reputation: 1269493
Use count(distinct)
:
select ug.*, count(distinct u.id) as user_count, count(distinct o.id) as order_count
from user_groups ug left join
users u
on ug.id = u.group_id left join
orders o
on u.id = o.user_id
group by ug.id;
count(id)
counts the number of non-NULL
values. You apparently want to count the number of different values, which is what distinct
does.
Upvotes: 2