Problem Solver
Problem Solver

Reputation: 385

MySQL concatenate values from one table into a record of another

I have three tables (many to many relationship): items, items_to_tags, and tags. The items and tags tables have a unique ID column, and the items_to_tags table has columns item_id and tag_id. Is there a way to select all results from the items and tags tables, but with all results merged into the same record?

For instance, if I have this data:

The result of the query should be:

item_id   item_name   tags
1         'item1'     'tag1,tag2,tag3'

Upvotes: 3

Views: 2201

Answers (2)

Taryn
Taryn

Reputation: 247700

You can use the MySQL GROUP_CONCAT():

select i.id,
  i.name,
  group_concat(t.name SEPARATOR ', ') tags
from items i
left join items_to_tags it
  on i.id = it.item_id
left join tags t
  on it.tag_id = t.id
group by i.id, i.name

See SQL Fiddle with Demo

Result:

| ID |  NAME |             TAGS |
---------------------------------
|  1 | item1 | tag1, tag2, tag3 |
|  2 | item2 |             tag3 |

Upvotes: 6

Madbreaks
Madbreaks

Reputation: 19539

This can be accomplished using MySQL's GROUP_CONCAT.

Upvotes: 0

Related Questions