insert into node(name) values($name); # 查所有父节点,建立关系 ids[] = {$parent_id} ids[] +=select id from node where current_id=$parent_id; distance = ids.length; for (ancestor_id : ids) { insert into relation(current_id, ancestor_id, distance) values ($id, $ancestor_id, $distance); distance--; }
id
name
13
file_l
14
file_j
15
file_k
16(add)
file_ADD
current_id
ancestor_id
distance
16
1
4
16
3
3
16
10
2
16
13
1
删
代价:-> O(n)
输入:id
执行:
ids[] = {$id} ids += $(select id from relation where ancestor_id = ${id}) deletefrom relation where ancestor_id in ${ids} or current_id in ${ids} deletefrom node where id in ${ids}
改
代价:-> O(1)
输入:id, other info
执行:
update node set info where id = $id
查
查自己
代价:-> O(1)
输入:id
执行:
select*from node where id = $id
查下一级
代价:-> O(n)
输入:id
执行:
select*from relation leftjoin node on node.id = relation.current_id where relation.ancestor_id = $id and distance =1
查所有子集
代价:-> O(n)
输入:id
执行:
select*from relation leftjoin node on node.id = relation.current_id where relation.ancestor_id = $id
移动
代价:-> O(n)
输入:id, new_parent_id
执行:
old_parent_id =select ancestor_id from relation where current_id = $id and distance =1; DEL # 执行上面的删除操作
objects = ${object(id)} objects += $(select current_id, distance from relation where ancestor = $id) for (object : $objects) { INSERT # 执行上面的插入操作 }