且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL 将一个表中的值连接到另一个表的记录中

更新时间:2023-01-08 16:51:00

您可以使用 MySQL GROUP_CONCAT():

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

参见SQL Fiddle with Demo

结果:

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