Sql question: Getting Parent rows followed by child rows

前端 未结 3 1253
逝去的感伤
逝去的感伤 2021-01-24 10:57

id parent_id

1 0

2 0

3 2

4 0

5 1

6 0

I need a query that will return parent rows (parent_id=0) f

3条回答
  •  离开以前
    2021-01-24 11:16

    You'd use a recursive CTE for this:

    WITH r AS 
     (SELECT id, 
        NULL AS parent_id, 
        CAST(right('000' + CAST(row_number() 
             OVER (table.id) AS varchar), 3) AS varchar(50))
      FROM table WHERE parent IS NULL
    
      UNION ALL
    
      SELECT table.id, table.parent_id, 
        CAST(r.ord + right('000' + CAST(row_number() 
             OVER (ORDER BY table.id) AS varchar), 3) AS varchar(50))
      FROM r JOIN table 
       ON table.parent = r.id)
    
     SELECT id 
     FROM r
     ORDER BY left(ord + '000000000000000000000000000000000', 36)
    

    Note that this particular version will break if any ID has a value greater than 999, and it will break if you have more than 12 levels. If this is a concern to you, you need to adjust the number of zeroes in the various places.

    There might be better ways, but this one works.

提交回复
热议问题