我有一个表 person 这些列,彼此依赖。
person_id, related_person_id, beginner_related_person_id
我的数据示例
person_id related_person_id beginner_related_person_id
1 null null
2 1 null
3 2 null
4 null null
5 4 null
6 null null
此列beginner_related_person_id是新的,现在为null。
我必须使用person_id中的值更新此行,但是必须使用root person_id。
person_id related_person_id beginner_related_person_id
1 null null
2 1 1
3 2 1
4 null null
5 4 4
6 null null
我已经开始编写查询但需要提示。
update person
set beginner_related_person_id = person_id
where person_id in (select distinct person_id from person start with related_person_id in (select person_id from person)
connect by prior beginner_person_id = person_id);
我应该使用循环吗?或其他什么?
答案 0 :(得分:0)
您可以使用MERGE
语句轻松完成此操作。
merge into person using (
select person_id,
related_person_id,
nullif(connect_by_root person_id, person_id) new_beginner_related_id
from person
start with
related_person_id is null
connect by
related_person_id = prior person_id ) u
on ( t.person_id = u.person_id )
when matched then
update set
t.beginner_related_person_id = u.new_beginner_related_id;