SQL获取所有相关行

时间:2017-05-10 01:14:22

标签: sql sql-server

我一直试图(非常缓慢地)在过去两周内弄清楚如何提出一种更好的方法来查询ID的所有相关行。我的公司处于一种情况,一个品牌不断被重命名,我们没有选择修改以前记录(在其他一些表格中)指向被替换的品牌。

我制作了一个小版本的桌子,以帮助邀请人们查看:

CREATE TABLE #GrwHist
(
    ID INT
    , Acronym VARCHAR(50)
    , New_ID INT
)

INSERT INTO #GrwHist VALUES(1,'ABC',33)
INSERT INTO #GrwHist VALUES(21,'GST',NULL)
INSERT INTO #GrwHist VALUES(33,'MnY',48)
INSERT INTO #GrwHist VALUES(37,'FWR',89)
INSERT INTO #GrwHist VALUES(48,'DMZ',89)
INSERT INTO #GrwHist VALUES(89,'PLT',106)
INSERT INTO #GrwHist VALUES(106,'TnI',NULL)
INSERT INTO #GrwHist VALUES(120,'YIZ',143)
INSERT INTO #GrwHist VALUES(143,'INZ',NULL)

SELECT * FROM #GrwHist
/*
ID  Acronym New_ID
--- ------- ------- 
1   ABC     33
21  GST     NULL
33  MnY     48
37  FWR     89
48  DMZ     89
89  PLT     106
106 TnI     NULL
120 YIZ     143
143 INZ     NULL
*/

DECLARE @ID INT
SET @ID = 106

SELECT * FROM #GrwHist WHERE ID = @ID
UNION
SELECT * FROM #GrwHist WHERE New_ID in (@ID)
UNION
SELECT * FROM #GrwHist WHERE New_ID in (SELECT ID FROM #GrwHist WHERE New_ID in (@ID))
UNION
SELECT * FROM #GrwHist WHERE New_ID in (
    SELECT ID FROM #GrwHist WHERE New_ID in (SELECT ID FROM #GrwHist WHERE New_ID in (@ID))
)
UNION
SELECT * FROM #GrwHist WHERE New_ID in (
    SELECT ID FROM #GrwHist WHERE New_ID in (SELECT ID FROM #GrwHist WHERE New_ID in (SELECT ID FROM #GrwHist WHERE New_ID in (@ID)))
)
UNION
SELECT * FROM #GrwHist WHERE New_ID in (
    SELECT ID FROM #GrwHist WHERE New_ID in (SELECT ID FROM #GrwHist WHERE New_ID in (SELECT ID FROM #GrwHist WHERE New_ID in (SELECT ID FROM #GrwHist WHERE New_ID in (@ID))))
) --And it grows and grows...
GO
DROP TABLE #GrwHist

最后一个查询基本上是:

--If I need to get all IDs related to a given ID I will get the following results:
@ID = 106 --> 106, 89, 48, 37, 33, 1
@ID = 143 --> 143, 120
@ID = 21 --> 21

这个查询的问题是可能有超过7-8个级别,我想知道我是否可以动态执行此操作,因此如果每次有另一个需要更改我的代码时我都不会担心添加了具有关系的行。假如是否添加了一行来替换ID为106的新行,我将不得不继续添加。

提前感谢您的任何帮助

1 个答案:

答案 0 :(得分:1)

您可以使用递归CTE来获取匹配项:

resize

编辑:

如果有重复项,您可以使用以下方式获取每个ID:

library(likert)
Loading required package: ggplot2
Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) : 
  there is no package called ‘tibble’
Error: package ‘ggplot2’ could not be loaded

获取一行的值有点复杂。