I have drawn a simple ERD:
The query I perform:
select s.*, count(c.store_id), count(p.store_id)
from store s
inner join customer c on c.store_id = s.id
inner join product p on p.store_id = p.id
group by s.id, s.store_name, s.address
The result:
id | store_name | address | count(c.store_id) | count(p.store_id) |
---|---|---|---|---|
1 | store1 | place | 12 | 12 |
2 | store2 | place | 4 | 4 |
3 | store3 | place | 29 | 29 |
4 | store4 | place | 9 | 9 |
Why do the counts give back the same number?
Every row has the same number for both count functions.
Did I mess up by joining customer and product on the same id field from store?
2
Answers
on the second join, you are joining product with itself
p.store_id = p.id
Simple data :
Then use
LEFT JOIN
, andCOUNT(DISTINCT ...id)
to eliminate duplicates :To check if a store has customers/products :
Result :
To get number of customers/products per store :
Result :
Demo here
You can simply use correlated subqueries to count:
Alternatively,
GROUP BY
in derived tables before joining: