我有两个表:

Table1:
id (uniqueidentifier, primarykey)
title (varchar(50))

Table2:
id (uniqueidentifier, primarykey)
table1id (uniqueidentifier, foreignkey to table1)
category (varchar(50))


我还具有以下SQL,可以将Table1的所有结果以及Table2的所有相应类别返回给我。

select t1.*, t2.category as cat from table1 as t1
left join table2 as t2 on t1.id = t2.table1id


问题是,类别可能有多个结果,那么如何用逗号将它们连接到cat列中呢?

例如,表2可能包含以下数据:

Table2 row 1:
id = 1
table1id = 1
category = "abc"

Table2 row 2:
id = 2
table1id = 1
category = "def"


查看两个记录如何具有相同的table1idcategory的值不同。

如何用逗号连接两个(或多个)潜在值,并将其作为单个字符串返回到上述查询的结果列cat中?

Desired output:
t1.id = 1
t1.title = table1 title
cat = abc, def

最佳答案

group_concat上使用t2.category并按要选择的其他列分组。

select t1.id, t1.title, group_concat(t2.category) as cat from table1 as t1
left join table2 as t2 on t1.id = t2.table1id
group by t1.id, t1.title

关于mysql - SQL将联接的结果串联到列中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25464495/

10-09 22:55
查看更多