树 mysql,族谱树mysql

I'm trying to create a structure to store and read dogs pedigree using php and mysql.

I found on stackoverflow this kind of structure, and it seems to be efficient: Inbreeding-immune database structure

TABLE people (id, name, father_id, mother_id );

TABLE relatives ( person_id, ancestor_id );

Is it possible to retrieve simply a ordered tree or a subtree (for example 4 or 5 generations) starting by an id?

EDIT

I'm trying to get the data from using the first table...but with 4-5 generations the resulting query is very very heavy. I fear that with a large amount of information in the DB, getting the genealogy could be to much slow and unusable.

SELECT

t1.name AS lev1, t2.name as f, ff1.name as ff1, fm1.name as fm1, t3.name as m,

mf1.name as mf1, mm1.name as mm1, .......

FROM people AS t1

LEFT JOIN people AS t2 ON t2.id = t1.father_id

LEFT JOIN people AS ff1 ON ff1.id = t2.father_id

LEFT JOIN people AS fm1 ON fm1.id = t2.mother_id

...

LEFT JOIN people AS t3 ON t3.id = t1.mother_id

LEFT JOIN people AS mf1 ON mf1.id = t3.father_id

LEFT JOIN people AS mm1 ON mm1.id = t3.mother_id

...

WHERE t1.id = 6;

解决方案

This sort of this is probably better suited for a graph style of data store. Something akin to how facebook keeps hierarchies of relationships.

If you are bound and determined to use MySQL you could probably get away with your schema by using a recursive search. Since your tree can be of variable depth you could start self-joining at given location and 'walk' down a branch recursing until you didn't find anymore descendants. Return that branch and start down the next one. Similar process for traversing up to find parents.

你可能感兴趣的:(树,mysql)