2012-02-15 64 views
1

我使用這個MySQL查詢拉回來一個結果,然後從連接結果聯接:我如何使用GROUP_CONCAT並獲得多個結果與聯接

SELECT card_name, GROUP_CONCAT(DISTINCT cat_name SEPARATOR ',') AS catcsv 
FROM `cards` 
LEFT JOIN card2cat ON cards.cards_id = card2cat.card2cat_card 
LEFT JOIN cats ON card2cat.card2cat_cat = cats.cats_id 
WHERE `card_id` = 1 

這將返回:

card_name catcsv 
----------------------------- 
Violets  Floral, Occasion 

這是完美的我需要什麼......不過,我需要得到相同的結果,但對於多個結果,像這樣:

SELECT card_name, GROUP_CONCAT(DISTINCT cat_name SEPARATOR ',') AS catcsv 
FROM `cards` 
LEFT JOIN card2cat ON cards.cards_id = card2cat.card2cat_card 
LEFT JOIN cats ON card2cat.card2cat_cat = cats.cats_id 
LIMIT 0, 10 

..但返回此:

card_name catcsv 
----------------------------- 
Violets  Floral, Occasion, Birthday, Down at the Farm, Cats and Dogs, Down at the Yard, Humour, Beach, Coast and Harbour, Gardening 

即所有可能的貓:(我已經試過刪除幾個不同的,它更糟糕,並返回每個類別多次!

我上面使用的結構/名稱被簡化爲張貼,所以在這裏粘貼一個數據庫結構轉儲並不太實際,我希望我已經解釋得很好了!

回答

2

你只是缺少GROUP BY條款:

SELECT card_name, GROUP_CONCAT(DISTINCT cat_name SEPARATOR ',') AS catcsv 
FROM `cards` 
LEFT JOIN card2cat ON cards.cards_id = card2cat.card2cat_card 
LEFT JOIN cats ON card2cat.card2cat_cat = cats.cats_id 
GROUP BY card_name 
LIMIT 0, 10 
+0

你DUDE!完善。我無法理解爲什麼這樣有效,因爲它看起來像是已經由catcsv分組了,但它確實如此。好男人先生! – 2012-02-16 14:39:04

相關問題