Getting hierarchy data from a self-referencing table

Posted by Emanuil on Stack Overflow See other posts from Stack Overflow or by Emanuil
Published on 2010-02-04T13:26:35Z Indexed on 2010/03/18 10:41 UTC
Read the original article Hit count: 438

Filed under:
|
|
|

Let's say you have the following table:
items(item_id, item_parent)
... and it is a self-referencing table as item_parent refers to item_id.

What SQL query would you use to SELECT all items in the table along with their depth where the depth of an item is the sum of all parents and grand parents of that item.

If the following is the content of the table:

item_id     item_parent
----------- -----------
1           0          
2           0            
3           2          
4           2          
5           3          

... the query should retrieve the following set of objects:

{"item_id":1,"depth":0}
{"item_id":2,"depth":0}
{"item_id":3,"depth":1}
{"item_id":4,"depth":1}
{"item_id":5,"depth":2}

P.S. I'm looking for a MySQL supported approach.

© Stack Overflow or respective owner

Related posts about sql

Related posts about database-queries