如何使用 GROUP_CONCAT 并通过连接获取多个结果
我正在使用这个 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,它甚至更糟并且多次返回每个类别!
我上面使用的结构/名称被简化用于发布,因此粘贴数据库结构转储在这里不太实用,我希望我已经解释得足够好了!?
I'm using this mysql query to pull back a single result, and concatenate the results from a join:
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
This returns:
card_name catcsv
-----------------------------
Violets Floral, Occasion
This is perfect for what I need... however I need to get the same results, but for multiple results like so:
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
..but that returns this:
card_name catcsv
-----------------------------
Violets Floral, Occasion, Birthday, Down at the Farm, Cats and Dogs, Down at the Yard, Humour, Beach, Coast and Harbour, Gardening
i.e ALL the possible cats :( I've tried removing DISTINCT and it's even worse and returns every category multiple times!
The structure/names I've used above are simplified for posting, so pasting a DB structure dump here isn't too practical, I hope I've explained it well enough!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只是缺少
GROUP BY
子句:You are just missing the
GROUP BY
clause: