我有两张桌子:
TableA ------ ID, Name TableB ------ ID, SomeColumn, TableA_ID (FK for TableA)
这种关系是一排TableA
- 许多TableB
.
现在,我希望看到这样的结果:
ID Name SomeColumn 1. ABC X, Y, Z (these are three different rows) 2. MNO R, S
这不起作用(子查询中有多个结果):
SELECT ID, Name, (SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID) FROM TableA
如果我在客户端进行处理,这是一个微不足道的问题.但这意味着我必须在每个页面上运行X查询,其中X是结果的数量TableA
.
请注意,我不能简单地执行GROUP BY或类似的操作,因为它将为行返回多个结果TableA
.
我不确定使用COALESCE或类似东西的UDF是否可行?
即使这样也会达到目的
样本数据
declare @t table(id int, name varchar(20),somecolumn varchar(MAX)) insert into @t select 1,'ABC','X' union all select 1,'ABC','Y' union all select 1,'ABC','Z' union all select 2,'MNO','R' union all select 2,'MNO','S'
查询:
SELECT ID,Name, STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX)) FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name FOR XML PATH('')),1,1,'') SOMECOLUMN FROM @T T1 GROUP BY id,Name
输出:
ID Name SomeColumn 1 ABC X,Y,Z 2 MNO R,S
CREATE FUNCTION CombineValues ( @FK_ID INT -- The foreign key from TableA which is used -- to fetch corresponding records ) RETURNS VARCHAR(8000) AS BEGIN DECLARE @SomeColumnList VARCHAR(8000); SELECT @SomeColumnList = COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) FROM TableB C WHERE C.FK_ID = @FK_ID; RETURN ( SELECT @SomeColumnList ) END
SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA
CREATE PROCEDURE GetCombinedValues @FK_ID int As BEGIN DECLARE @SomeColumnList VARCHAR(800) SELECT @SomeColumnList = COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) FROM TableB WHERE FK_ID = @FK_ID Select *, @SomeColumnList as SelectedIds FROM TableA WHERE FK_ID = @FK_ID END
我认为你与COALESCE走在正确的轨道上.有关构建逗号分隔字符串的示例,请参见此处:
http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string
在MySQL中有一个group_concat函数,它将返回您要求的内容.
SELECT TableA.ID, TableA.Name, group_concat(TableB.SomeColumn) as SomColumnGroup FROM TableA LEFT JOIN TableB ON TableB.TableA_ID = TableA.ID