我有這些表:MySQL的GROUP_CONCAT與限制,並加入
# tb_shops
shop_id PK
shop_name
# tb_products
product_id PK
product_name
shop_id FK
我需要列出所有的「商店」有4個產品,但一些商店已經超過4種產品。
我嘗試此查詢:
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
但是,它不能正常工作。它會返回重複的產品。如果我在group_concat
中使用distinct
,它不會附帶4種商店產品,真的很奇怪......有人知道更好的解決方案嗎?
子查詢返回表中的任何4行,而不是每個商店的4行。 – Barmar
請參閱http://stackoverflow.com/questions/2129693/mysql-using-limit-within-group-by-to-get-n-results-per-group瞭解如何爲每個組獲得4條記錄。 – Barmar
我看到有人說substring_index,但我認爲這是性能命中cuz也許一些商店可以有500個項目或1000和substring_index將只限制輸出,但這500個項目將進入查詢 – Awsj2hd8