第一个问题,设计数据架构:我使用父行的外键来保持层次结构。简直了。
第二个问题,检索祖先/后代:正如您所解释的,选择出现问题:选择一些人和所有后代的祖先。要解决这个问题,您应该创建一个新的树表。此表包含对:一个人与所有他们的祖先(和它自己)的组合:
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 **
你可以玩距离,只得到祖父母、孙子等......
最后一个问题,保持树:树必须随时掌握数据。您应该自动执行此操作:people 上的触发器或 CRUD 操作的存储过程,
已编辑
因为这是一棵家谱树,所以每个人都必须有参考资料,父母和母亲:
people( id, name, id_parent, id_mother)
那么,需要两棵树:
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 --
问候。