Dealing with nested sets in mysql?

最后都变了- 提交于 2019-11-30 20:10:26

To update/delete you will need to increase/decrease left/right values of all elements of branch.
Examples of queries you can find here.

How efficient it is I do not know.

Nested sets works VERY slowly with big trees on update/insert/delete. And very fast to select.
So use this model only with static data, which will be stored without changes most of the time, and this tree will not contain thousands of nodes (or any update will take minutes to complete). Materialized path works much faster.

  • to get the parents of a node you need nodes with left_id < child.left_id and right_id > child.right_id, if you only want the direct ancestor choose the one from previous set with the highest left_id.

  • to delete a node remove it and then lower twice all left/right ids that are greater than deleted element right id. if( leftId > deleted.leftId ) leftId-=2 same for rightId

  • to insert a node make some space for it adding+2 to all nodes with leftId > parent.rightId then parent.rightId += 2 then insert node with leftId = parent.rightId-2 and rightId=parent.rightId-1

All of your questions can be solved very easy if you use a DFS for each relationship and then use your function calculate() again if you want it more detailed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!