【发布时间】:2014-10-17 08:08:52
【问题描述】:
我有两张桌子:
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 的列中?
例如,Table2 可能包含以下数据:
Table2 row 1:
id = 1
table1id = 1
category = "abc"
Table2 row 2:
id = 2
table1id = 1
category = "def"
查看两条记录如何具有相同的table1id 但category 的值不同。
如何通过逗号连接两个(或多个)潜在值并将其作为单个字符串返回到上述查询的结果列 cat?
Desired output:
t1.id = 1
t1.title = table1 title
cat = abc, def
【问题讨论】: