How do you sort a tree stored using the nested set model?

前端 未结 8 849
不思量自难忘°
不思量自难忘° 2021-01-31 20:32

When I refer to nested set model I mean what is described here.

I need to build a new system for storing \"categories\" (I can\'t think of better word for it) in a user

8条回答
  •  情书的邮戳
    2021-01-31 20:44

    I think this is indeed a limitation of the nested set model. You can not easily sort the child nodes within their respective parent node, because the ordering of the result set is essential to reconstruct the tree structure.

    I think it is probably the best approach to keep the tree sorted when inserting, updating or deleting nodes. This even makes queries very fast, which is one of the main goals of this data structure. If you implement stored procedures for all operations, it is very easy to use.

    You can also reverse the sort order of a presorted tree. You just have to use ORDER BY node.rgt DESC instead of ORDER BY node.lft ASC.

    If you really need to support another sort criteria, you could possible implement it by adding a second lft and rgt index to each node and keep this sorted by the other criteria on every insert/update/delete.

提交回复
热议问题