gpt4 book ai didi

sql - 如何有效地连接多个表中的多行

转载 作者:行者123 更新时间:2023-12-05 00:25:48 26 4
gpt4 key购买 nike

我有多个表,其中一个主表有一个外键。表格是这样的:

姐妹们

MainID    IDNO   ....
111111 1 ....
111111 1 ....
111111 1 ....
222222 1 ....
111111 2 ....

兄弟

MainID    IDNO   ....
111111 555 ....
111111 333 ....
111111 111 ....
222222 222 ....
111111 321 ....

叔叔

MainID    IDNO   ....
111111 561 ....
111111 121 ....
111111 331 ....
222222 451 ....
111111 672 ....

我需要将所有 IDNo 连接起来,但我似乎无法获得全部,例如,我可能无法获得 672

SELECT 
',' + S1.IDNo + ',' + B1.IDNo + ',' + U1.IDNo AS [text()]
FROM
Sisters S1, Brothers B1, Uncles U1, MainTable
WHERE
D1.MainID = MainTable.ID
AND S1.MainID = MainTable.ID
AND B1.MainID = MainTable.ID
FOR XML PATH('')

我尝试分离表并在稍后连接,但这样做速度越来越慢。我能做什么?

预期输出:

,1,1,1,1,2,555,333,111,222,321,561,121,331,451,672

最佳答案

根据预期的输出,似乎 3 个表中每个表中的 MainID 列在输出中都没有发言权(如果是)那么这应该对您有用,但我不确定它是否会扩展处理 600K+ 记录。出于好奇,为什么要连接如此大的值列表?

Declare @x as varchar(max) = ''

SELECT @x = @x + ',' + CAST(A.IDNO as varchar) FROM
(
select 1 as IDNO UNION ALL
select 2 as IDNO UNION ALL
select 3 as IDNO UNION ALL
select 4 as IDNO
) A -- Pretend this is your Sisters tables
FOR XML PATH('')
PRINT @X -- Just for Debugging Purposes

SELECT @x = @x + ',' + CAST(B.ID as varchar) FROM
(
select 55 as IDNO UNION ALL
select 66 as IDNO UNION ALL
select 77 as IDNO UNION ALL
select 88 as IDNO
) B -- Pretend this is your Brothers tables

PRINT @X -- Just for Debugging Purposes

SELECT @x = @x + ',' + CAST(C.IDNO as varchar) FROM
(
select 555 as IDNO UNION ALL
select 666 as IDNO UNION ALL
select 777 as IDNO UNION ALL
select 888 as IDNO
) C -- Pretend this is your Uncles tables


PRINT @X -- Final Output
SELECT @X as XML_Output FOR XML PATH('')

输出:

,1,2,3,4
,1,2,3,4,55,66,77,88
,1,2,3,4,55,66,77,88,555,666,777,888 -- Final Result

<XML>,1,2,3,4,55,66,77,88,555,666,777,888</XML> -- XML Output

所以在你的情况下你可以做这样的事情(再次不确定它在大 table 上的表现如何):

Declare @x as varchar(max) = ''
SELECT @x = @x + ',' + CAST(A.IDNO as varchar) FROM
(
select MainID , IDNO FROM SISTERS UNION ALL
select MainID , IDNO FROM BROTHERS UNION ALL
select MainID , IDNO FROM UNCLES
) A


SELECT @X as XML_Output FOR XML PATH('')

关于sql - 如何有效地连接多个表中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38638365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com