on the second join, you are joining product with itself p.store_id = p.id
Simple data :
CREATE TABLE store (
id int,
store_name varchar(20),
address varchar(20)
);
insert into store values
(1,'store1','address1'),
(2,'store2','address2'),
(3,'store3','address3');
CREATE TABLE product (
product_name int,
store_id int
);
insert into product values
(1,1),
(2,1);
CREATE TABLE customer (
customer_name int,
store_id int
);
insert into customer values
(1,2),
(2,2);
Then use LEFT JOIN
, and COUNT(DISTINCT ...id)
to eliminate duplicates :
To check if a store has customers/products :
select s.*, count(DISTINCT c.store_id), count(DISTINCT p.store_id)
from store s
left join customer c on c.store_id = s.id
left join product p on p.store_id = s.id
group by s.id, s.store_name, s.address
Result :
id store_name address count(c.store_id) count(p.store_id)
1 store1 address1 0 1
2 store2 address2 1 0
3 store3 address3 0 0
To get number of customers/products per store :
select s.*, count(DISTINCT c.customer_name) as number_customers, count(DISTINCT p.product_name) as number_products
from store s
left join customer c on c.store_id = s.id
left join product p on p.store_id = s.id
group by s.id, s.store_name, s.address
Result :
id store_name address number_customers number_products
1 store1 address1 0 2
2 store2 address2 2 0
3 store3 address3 0 0
Demo here