Join a table to itself

后端 未结 7 1252
Happy的楠姐
Happy的楠姐 2021-01-26 00:15

this is one on my database tables template.

Id int PK
Title nvarchar(10) unique
ParentId int 

This is my question.Is there a problem if i creat

7条回答
  •  被撕碎了的回忆
    2021-01-26 00:48

    You can perfectly join the table with it self.

    You should be aware, however, that your design allows you to have multiple levels of hierarchy. Since you are using SQL Server (assuming 2005 or higher), you can have a recursive CTE get your tree structure.

    Proof of concept preparation:

    declare @YourTable table (id int, parentid int, title varchar(20))
    
    insert into @YourTable values
    (1,null, 'root'),
    (2,1,    'something'),
    (3,1,    'in the way'),
    (4,1,    'she moves'),
    (5,3,    ''),
    (6,null, 'I don''t know'),
    (7,6,    'Stick around');
    

    Query 1 - Node Levels:

    with cte as (
        select Id, ParentId, Title, 1 level 
        from @YourTable where ParentId is null
    
        union all
    
        select yt.Id, yt.ParentId, yt.Title, cte.level + 1
        from @YourTable yt inner join cte on cte.Id = yt.ParentId
    )
    select cte.*
    from cte 
    order by level, id, Title
    

提交回复
热议问题