繁体   English   中英

SQL将联接的结果串联到列中

[英]SQL Concatenate Joined Results into Column

我有两个表:

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上使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM