如何使用GROUP_CONCAT并通过连接获得多个结果

时间:2012-02-15 14:14:06

标签: mysql distinct

我正在使用这个mysql查询来取回一个结果,并连接来自连接的结果:

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

即所有可能的猫:(我已经尝试删除DISTINCT,它甚至更糟,并且多次返回每个类别!

我上面使用的结构/名称都是为了发布而简化的,所以在这里粘贴数据库结构转储并不太实际,我希望我已经解释得很好了!?

1 个答案:

答案 0 :(得分: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