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!?
You are just missing the
GROUP BYclause: