954
社区成员
发帖
与我相关
我的任务
分享
-- 1. 如果想从头来过,先清空祖级id字段
UPDATE `sys_dept`
SET `ancestors` = NULL;
-- 2. 设置:根节点的祖级
update `sys_dept` t set t.ancestors= '0'
where t.parent_id = 0;
-- 3. 重复执行(直到受影响的行: 0):其他节点的祖级 = 父节点.ancestors + 父节点.id
update `sys_dept` t
left join `sys_dept` pt
on t.parent_id = pt.dept_id
set t.ancestors = concat(pt.ancestors, ',', pt.dept_id)
where t.parent_id != 0;
参照上述代码我写了PSQL下的祖级更新语句,但有个问题,跟上述代码一样,需要重复执行多次,人工去审核是否完全更新了祖级,这个该如何改造通过执行一次就更新了全部的祖级列表呢?
表上添加trigger,级联更新也可以
使用 WITH RECURSIVE 递归生成各级ancestors,然后做个JOIN更新就行了
递归查询参考:http://postgres.cn/docs/12/queries-with.html