MySQL 将一个表中的值连接到另一个表的记录中 [英] MySQL concatenate values from one table into a record of another
本文介绍了MySQL 将一个表中的值连接到另一个表的记录中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个表(多对多关系):items
、items_to_tags
和 tags
.items
和 tags
表有一个唯一的 ID 列,items_to_tags
表有列 item_id
和 tag_id
.有没有办法从 items
和 tags
表中选择所有结果,但所有结果都合并到同一条记录中?
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:
项目
:
id name
1 'item1'
2 'item2'
标签
:
id name
1 'tag1'
2 'tag2'
3 'tag3'
items_to_tags
:
item_id tag_id
1 1
1 2
1 3
2 3
查询结果应该是:
item_id item_name tags
1 'item1' 'tag1,tag2,tag3'
推荐答案
您可以使用 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
结果:
| ID | NAME | TAGS |
---------------------------------
| 1 | item1 | tag1, tag2, tag3 |
| 2 | item2 | tag3 |
这篇关于MySQL 将一个表中的值连接到另一个表的记录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文