Getting hierarchy data from self-referencing tables

情到浓时终转凉″ 提交于 2019-11-27 11:15:40

问题


Let's say you have the following table:

items(item_id, item_parent)  

... and it is a self-referencing table - 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.


回答1:


If the database is SQL 2005 / 2008 then...

The easiest way to get this is using a CTE (Common Table Expression) that is designed to recurse.

 WITH myCTE (Item_id, Depth)
 AS
 (
    Select Item_ID, 0 as Depth From yourTable where Item_Parent=0
    Union ALL
    Select yourTable.Item_ID, Depth + 1 
    From yourTable 
    inner join myCte on yourTable.item_Parent = myCte.Item_Id
 )

 Select Item_id, Depth from myCTE

The output is as follows:

Item_Id  Depth
    1   0
    2   0
    3   1
    4   1
    5   2

From that you can format it as you wish.




回答2:


There is a good tech article on the mysql website about hierarchical data in MySql: Managing Hierarchical Data in MySQL - you can find a few detailed solutions with pro and cons there.

Especially the part about "The Nested Set Model" and "Finding the Depth of the Nodes" should be of interest for you.




回答3:


Oracle has a very convenient syntax for retrieving hierarchical data like this:

select
    item_id,
    item_parent,
    level as depth
from
    items
connect by
    prior item_id = item_parent
start with
    item_parent not in (select item_id from items)

This starts with the root nodes of your trees as those items whose item_parent does not exist in the table as item_id, and selects all children of those nodes, along with their depth in the tree.




回答4:


MySQL

  • http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html
  • http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

EDIT: removed unnecessary information




回答5:


I need to find a solution for the same task, found some articles, but still didn't choose which way to go...

http://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/

May be these links might help you. If you find a good solution - please post it here. i'm not allowed to post more then 1 link - i will add some to next posts



来源:https://stackoverflow.com/questions/2199942/getting-hierarchy-data-from-self-referencing-tables

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