I have these tables:
# tb_shops
shop_id PK
shop_name
# tb_products
product_id PK
product_name
shop_id FK
I need to list all 'shops' with 4 products but some shops has more than 4 products.
I tried this query:
select a.shop_id,
a.shop_name,
count(b.product_id) as ptotal,
group_concat(c.product_name separator ',') as products
from tb_shops a
left join tb_products b on a.shop_id=b.shop_id
left join (
select product_name,shop_id
from tb_products
limit 4) as c
on a.shop_id=c.shop_id
group by a.shop_id
order by a.shop_name asc
But, it doesn't work properly. It returns duplicate products. If I use distinct
in group_concat
it doesn't come with 4 products of the shop, really strange... someone knows a better solution?