我有两张桌子:
- tb_shops
shop_id PK
shop_name
- tb_products
product_id PL
product_name
shop_id FK
我需要列出类似的内容:
shop_name | product01,product02,product03,product04
shop_name2 | product05,product06,product07,prodcut08
但这些产品每个商店需要限制4个。
我试过这些问题:
使用子查询进行拳击
select SQL_NO_CACHE a.shop_id,
a.shop_name,
count(b.product_id) as ptotal,
(select group_concat(_b.product_name separator ',') from tb_shops _a left join tb_products _b using(shop_id) where _a.shop_id=a.shop_id group by _a.shop_id limit 4) as products
from tb_shops a
left join tb_products b on a.shop_id=b.shop_id
group by a.shop_id
order by a.shop_name asc
第二个是substring_index
select SQL_NO_CACHE a.shop_id,
a.shop_name,
count(distinct b.product_id) as ptotal,
substring_index(group_concat(distinct c.product_name separator ','),',',4) as products
from tb_shops a
left join tb_products b on a.shop_id=b.shop_id
left join tb_products c on a.shop_id=c.shop_id
group by a.shop_id
order by a.shop_name asc
哪些更好?或者有人知道更好的解决方案?