Recursive MySQL query?

可紊 提交于 2019-11-27 14:54:39

MySQL doesn't support recursive queries.

I would suggest that you look at Bill Karwin's presentation where he compares four different models for storing heirarchical data and looks at their pros and cons:

  • Adjacency list
  • Path enumeration
  • Nested sets
  • Closure table

Slide 48 shows the relative difficulty of certain types of queries with each of the models. From your question it sounds like you are interested most in "Query subtree", for which the adjacency list (the model you are currently using) performs the most poorly of the four.

Alternatively if you just want to select the entire tree, as in all data in the table, then you could use the simple query SELECT * FROM yourtable and reconstruct the tree structure in the client.

need more data.. does the table only represent a single tree, or multiple trees? If it's a single tree, you can just select everything from the table, then build the tree structure in memory. If it is multiple trees, you could consider adding a treeID to each tree element to represetn the tree the element belongs to.

If you are looking to select a branch of a tree, you can consider storing elements with sequential integer "sort ranks" and links to the left and right nodes, then selecting all nodes within the integer range of the left most node and right most node.

Look up adjacency list for more information on this storage model. You can also create a hybrid adjacency list/ parent node link, since data storage is so cheap, but you may have more overhead keeping sort links updated...

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