【问题标题】:Find Pairs in recursive table [duplicate]在递归表中查找对[重复]
【发布时间】:2018-06-25 01:53:42
【问题描述】:

我有以下表格

CREATE TABLE [dbo].[MyTable2](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ParentID] [int] NOT NULL,
)

我尝试创建一个查询,该查询将返回一对 ID、ParentID 的列表。例如我有以下数据

ID  ParentID
1   0
2   0
3   1
4   3
5   3
15  8

当我按 ID = 5 搜索时,我希望有以下列表:

ID  ParentID
5   3
3   1
1   0

如果我按 ID = 15 搜索,它应该会看到该序列是 boken 并且我将获得以下关注列表。

ID  ParentID
15  8

为了让它工作,我使用了一个临时表,我的代码如下:

if object_id('tempdb..#Pairs') is not null
    DROP TABLE #Pairs
create table #Pairs
( 
    ID INT,
    ParentID INT
)
Declare @ID integer = 5;
Declare @ParentID integer;
while (@ID > 0)
BEGIN
  SET @ParentID = null;             -- I set it to null so that I will be able to check in case the sequence is broken
  select @ID=ID, @ParentID=ParentID
  from MyTable
  where ID = @ID;

  if @ParentID IS NOT null 
  begin
  Insert into #Pairs (ID, ParentID) Values (@ID, @ParentID)
  SET @ID = @ParentID;
  end
  else
    SET @ID = 0;
END
SELECT * from #Pairs

它有效,但我确信有更好的方法来做到这一点。我发现了一些奇怪的查询,它们应该做类似的事情,但我无法转换它以满足我的需求。

例如,我发现了以下问题,但无法将其转换为与我的表格一起使用。我发现的所有查询都有相似的答案。

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    您正在寻找递归查询。请参见以下示例:

    SELECT * INTO tab FROM (VALUES
    (1, 0),
    (2, 0),
    (3, 1),
    (4, 3),
    (5, 3),
    (15, 8)) T(ID, ParentID);
    
    DECLARE @whatAreYouLookingFor int = 5;
    
    WITH Rec AS
    (
        SELECT * FROM tab WHERE ID=@whatAreYouLookingFor
        UNION ALL
        SELECT T.* FROM tab T JOIN Rec R ON R.ParentID=T.ID
    )
    SELECT * FROM Rec;
    
    DROP TABLE tab
    

    输出:

    ID  ParentID
    --  --------
    5   3
    3   1
    1   0
    

    【讨论】:

    • 谢谢。你是救生员。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多