Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

database - How to query graph/hierarchical data in mysql

Suppose I have a table of objects structured in a hierarchy:

A
|--B
|--C
|  +--D
+--E

They are stored in a "parent-child" table thus:

parent  child
A       B
A       C
C       D
A       E

How do I query this to get the structure defined above? I think I need something that produces info like this:

object  full_path
A       NULL
B       A
C       A
D       A.C
E       A

I cannot figure out how to do the objects nested more than one level deep. It feels like I might need to iterate over the table (no idea if this is possible in SQL), or otherwise use some kind of query I've never encountered before.

Additional Info:

  1. A need not be the only orphan object.
  2. Children may have multiple parents BUT for now I'm happy with an answer to whichever scenario is easier to solve. I can abide converting a multi-parent structure to a single parent with a simple GROUP BY and MIN statement.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The other answers are correct, there is no recursive functionality in mysql. This link describes how to approach hierarchies in mysql: http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/

I found the link on two other SO questions: How to do MySQL Looped Join which tests if results are complete? and Hierarchical Data in MySql .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...