How do I sort a linked list in sql?

后端 未结 4 763
遇见更好的自我
遇见更好的自我 2020-12-08 07:45

I have implemented a linked list as a self-referencing database table:

CREATE TABLE LinkedList(
    Id bigint NOT NULL,
    ParentId bigint NULL,
    SomeDat         


        
4条回答
  •  生来不讨喜
    2020-12-08 08:27

    In Oracle:

    SELECT Id, ParentId, SomeData
    FROM (
      SELECT ll.*, level AS lvl
      FROM LinkedList ll
      START WITH
        ParentID IS NULL
      CONNECT BY
        ParentId = PRIOR Id
    )
    ORDER BY
      lvl
    

    P. S. It's a bad practice to use NULL as ParentID, as it is not searchable by indices. Insert a surrogate root with id of 0 or -1 instead, and use START WITH ParentID = 0.

提交回复
热议问题