MYSQL output in tree format OR Adding level (Parent-Child)

后端 未结 4 1878
失恋的感觉
失恋的感觉 2020-12-19 21:25

Below is what I have in my table.

myTable

++++++++++++++++++++
Parent   +  Child
++++++++++++++++++++
  C1     +    G1
  C1     +    G2
  C1     +          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 21:53

    first Create Recursive function for calc level.

    function fn_CalcLevel(int @ID) 
    As Begin
      Declare @ParentID int
      Select @ParentID = ParentID From Table1 where ID = @ID
    
      IF (@ParentID IS NULL) Return 1 Else Return 1+fn_CalcLevel(@ParentID)
    End
    

    then Create your Query Such as Below

    Select *, fn_CalcLevel(Table1.ID) as Level
    From Table1
    

提交回复
热议问题