第一个问题,设计数据模式:我将层次结构保留为父行的外键.这很简单.
第二个问题,检索后代/后代:正如你解释的那样,问题来自于选择:选择一些人和所有后代的后代.要解决此问题,您应该创建一个新的树表.此表包含对:与具有所有祖先(及其自身)的人的组合:
people( id, name, id_parent)
people_tree( id, id_ancestor, distance )
注意,使用此结构很容易查询层次结构.示例:某人的所有后代:
select people.*, distance
from
people p
inner join
people_tree t
on ( p.id = t.id)
where
id_ancesor = **sombody.id **
你可以与远方玩,只有祖父母,孙子女等…
最后一个问题,保持树:树必须始终是数据.您应该自动执行此操作:触发人员或CRUD操作的存储过程,
EDITED
因为这是一个家谱树,每个人必须有两个参考,父母和母亲:
people( id, name, id_parent, id_mother)
然后,需要2棵树:
parent_ancestors_tree( id, id_ancestor, distance )
mother_ancestors_tree( id, id_ancestor, distance )
大卫要求提供样本数据:
people: id name id_parent id_mother
1 Adam NULL NULL
2 Eva NULL NULL
3 Cain 1 2
.. ...
8 Enoc 3 5
parent_ancestors_tree id id_ancestor distance
(Adam) 1 1 0
(Eva) 2 2 0
(Cain) 3 3 0
3 1 1
(Enoc) 8 8 0
8 3 1
8 1 2
mother_ancestors_tree id id_ancestor distance
(Adam) 1 1 0
(Eva) 2 2 0
(Cain) 3 3 0
3 2 1
(Enoc) 8 8 0
-- here ancestors of Enoc's mother --
问候.