views:

162

answers:

4

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?

A: 

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://

cvista
A: 

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/

Eimantas
A: 

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:

Quassnoi
A: 

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).

Pekka