How to represent a data tree in SQL?

后端 未结 8 856
星月不相逢
星月不相逢 2020-12-02 06:20

I\'m writing a data tree structure that is combined from a Tree and a TreeNode. Tree will contain the root and the top level actions on the data. I\'m using a UI library to

8条回答
  •  我在风中等你
    2020-12-02 06:43

    The easiest implementation is adjacency list structure:

    id  parent_id  data
    

    However, some databases, particularly MySQL, have some issues in handling this model, because it requires an ability to run recursive queries which MySQL lacks.

    Another model is nested sets:

    id lft rgt data
    

    where lft and rgt are arbitrary values that define the hierarchy (any child's lft, rgt should be within any parent's lft, rgt)

    This does not require recursive queries, but it slower and harder to maintain.

    However, in MySQL this can be improved using SPATIAL abitilies.

    See these articles in my blog:

    • Adjacency list vs. nested sets: PostgreSQL
    • Adjacency list vs. nested sets: SQL Server
    • Adjacency list vs. nested sets: Oracle
    • Adjacency list vs. nested sets: MySQL

    for more detailed explanations.

提交回复
热议问题