2015-02-04 122 views
0

我有這些表: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種商店產品,真的很奇怪......有人知道更好的解決方案嗎?

+0

子查詢返回表中的任何4行,而不是每個商店的4行。 – Barmar

+0

請參閱http://stackoverflow.com/questions/2129693/mysql-using-limit-within-group-by-to-get-n-results-per-group瞭解如何爲每個組獲得4條記錄。 – Barmar

+0

我看到有人說substring_index,但我認爲這是性能命中cuz也許一些商店可以有500個項目或1000和substring_index將只限制輸出,但這500個項目將進入查詢 – Awsj2hd8

回答

0

嗯,我需要列出所有的「商店」有4個產品,但一些商店有 超過4產品

您可以使用having關鍵字,擺脫一些joins

select a.shop_id, 
     a.shop_name, 
     count(b.product_id) as ptotal, 
     group_concat(b.product_name separator ',') as products 
from tb_shops a 
join tb_products b on a.shop_id = b.shop_id 
group by b.shop_id 
having count(b.product_id) = 4 
order by a.shop_name asc; 

這將解決您的問題。基本上你在這裏做的是在botch表上正常的join,然後group by shop_id,最後只選擇其中的count等於4的那些。在這裏不需要使用兩個左連接。

+0

@ Awsj2hd8這個工作適合你嗎? –

+0

以及此查詢將顯示超過4個產品,看看有 – Awsj2hd8

+0

@ Awsj2hd8誤讀,編輯。 –