Select all parents or children in same table relation SQL Server

后端 未结 4 2072
日久生厌
日久生厌 2021-02-05 11:10

SQL developers, I have a badly planned database as task to learn a lot about SQL Server 2012.

SO, there is the table Elem:

+-----------+----         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 11:18

    I dont think it can be done in one select in whole case ,so that you can select all parents,grandparents ,... . One way how to do it is to join elem table to herself ,and thet it depends on how many levels of join you do , that level of childs,grandchilds will you get.

    The solution can be somethink like this(for the second case )

    this will select you all parents,childs and grandchilds

    Select 
    parent.key as parent_key,
    child.key as child_key,
    grandchild.key as grandchild_key 
    from elem parent 
    join elem child on (elem.key=child.parentkey)
    join elem grandchild on (child.key=grandchild.parentkey)
    where parent.parentkey is null; -- this make you sure that first level will be parents
    

    solution for the first case is just that you will connect tables not in style of 'key=parentkey' but oposite 'parentkey=key'.

提交回复
热议问题