我一直在用这个封闭表转圈子。我遇到的问题是第二次出现后代。我有出现在多个父类别中的子类别实例。为了简单起见,我回到了这个例子:
drop table if exists closure;
drop table if exists nodes;
create table nodes (
node int auto_increment primary key,
label varchar(20) not null
);
insert into nodes (node, label) values
(1, 'rootree'),
(2, '1stbranch'),
(3, 'midbranch'),
(4, 'corebranch'),
(5, 'leafnodes'),
(6, 'lastbranch'),
(7, 'lastleaf');
create table closure (
ancestor int not null,
descendant int not null,
primary key (ancestor, descendant),
foreign key (ancestor) references nodes(node),
foreign key (descendant) references nodes(node)
);
insert into closure (ancestor, descendant) values
(1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (1,7),
(2,2),
(3,3), (3,4), (3,5),
(4,4), (4,5),
(5,5),
(6,6), (6,7),
(7,7);
使用以下查询,我可以获得所需的结果:
select group_concat(n.label order by n.node separator ' -> ') as path
from closure d
join closure a on (a.descendant = d.descendant)
join nodes n on (n.node = a.ancestor)
where d.ancestor = 1 and d.descendant != d.ancestor
group by d.descendant;
结果:
rootree -> 1stbranch
rootree -> midbranch
rootree -> midbranch -> corebranch
rootree -> midbranch -> corebranch -> leafnodes
rootree -> lastbranch
rootree -> lastbranch -> lastleaf
但是如果我添加另一个孩子,例如一个已经存在的孩子,我想让叶子节点成为 roottree -> lastbranch -> lastleaf 的孩子
我在闭包表中插入两条新记录:(6-5)和(7-5)
然后所有的地狱都崩溃了。我已经尝试了我能想到的一切,但我没有得到任何地方。