第一个问题是设计数据模式 :我保留带有父行外键的层次结构。很简单。
第二个问题,检索上升/下降
:正如您所解释的,select带来的问题是:选择某些人和所有上升后代。为了解决这个问题,您应该创建一个新的树表。该表包含以下几对:一个人及其所有祖先(及其本身)的组合:
people( id, name, id_parent)people_tree( id, id_ancestor, distance )
注意,使用这种结构很容易查询层次结构。样本:某人的所有后代:
select people.*, distancefrom people p inner join people_tree t on ( p.id = t.id)where id_ancesor = **sombody.id **
您可以与远方玩耍,只让祖父母,孙子女等…
最后一个问题,保持树 :树必须 一直保持 数据。您应该自动执行此操作:
peopleCRUD操作的触发器或存储过程,
已编辑
因为这是家谱树,所以每个人都必须同时具有父母和母亲两个参考:
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 5parent_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 2mother_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 --
问候。



