-1

I have one table called forms and one table called categories. They have a many-to-many relationship through a category_form as pivot. The pivot table has form_id and category_id

So each form can have many categories and every category can be attached to many forms.

I need to aggregate this data somehow. What I need is a comma separated list of category id's in a column for each form.

Like this:

FORMS
id  | name | categories 
1   | f1   | 1,4,7
2   | f2   | 1
3   | f3   | 1,6,8,9

What would be an effective way of doing this?

Christoffer
  • 7,470
  • 9
  • 39
  • 55

1 Answers1

1

Try this:

SELECT f.id, f.name, GROUP_CONCAT(cf.category_id) AS categories
FROM forms f
INNER JOIN category_form cf ON f.id = cf.form_id
GROUP BY f.id, f.name
ORDER BY f.id;
nachospiu
  • 2,009
  • 2
  • 8
  • 12