MySQL - Recursing a tree structure

早过忘川 提交于 2019-11-26 17:48:59

问题


I have a database table which link locations together; a location can be in a location, which can be inside another location.

location (<id>, ....)
location_parent (<location_id>, <parent_id>)

Here's the MySQL/PHP to go down for a depth of one:

$sql = "SELECT id FROM se_locations_services WHERE parent_locationid IN
( SELECT location_id FROM se_locations_parent WHERE parent_id = '$locationid' )";

How do I, given a parent location, gets all its descendants locations, no matter how deep, just using MySQL?


回答1:


There's a good-looking article over at mysql.com outlining various ways of managing hierarchical data. I think it provides a full solution to your question, and shows various less simple, but faster approaches (e.g. Nested Sets).




回答2:


MySQL lacks native support of hierarchical functions, so you'll have to emulate them using session variables to keep the recursion state.

See this article on how to implement the function:

  • Hierarchical queries in MySQL



回答3:


A much better way of managing this sort of data is to use the Modified Preorder Tree Traversal technique:

http://articles.sitepoint.com/article/hierarchical-data-database/2

hth

w://




回答4:


Since mysql statements can return only table-structured data, how do you imagine the returned tree-structure?

It is possible to do a selection with [parent_id, child_id] table, but it requires temporary table and I've seen it done on DB2, not on MySQL.

Check this article for implementation on tree-like structures stored in MySQL: http://articles.sitepoint.com/article/hierarchical-data-database/



来源:https://stackoverflow.com/questions/2378678/mysql-recursing-a-tree-structure

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