我在 Oracle 中有 2 个表,其结构与这些类似:
族表
id member parent_id flag flight
---------------------------------
1 A null N null
2 B 1 N null
3 C null N null
4 D 3 N null
5 E 3 N null
6 F null N null
7 G 6 N null
飞行表
id family_id flight
-----------------------
1 1 1000
2 3 2000
这里,家庭表中 id 为 4,5 的行是第 3 行的子行,第 2 行是第 1 行的子行。
现在,我需要编写一个 oracle update sql 来不仅用航类更新相应的父行并将标志更改为 Y,而且子行也应该相应地更新。如果航类表中没有相应的家庭航类分配,则第 6、7 行应保持原样。
为 parent 更新 parent 和寻找 child 很容易。但是是否可以在一个 sql 中完成所有更新?
谢谢。
更新
update family fm set (flag, flight) =
(
select 'Y', fl.flight from flight fl where fm.flag <> 'Y' and
(
(fl.parent_id=fm.id and fm.parent_id is null )
or fm.parent_id=fl.parent_id
)
)
where exists (select 1 from flight fl where fm.id=fl.parent_id or fl.parent_id=fm.parent_id );
这行得通!!
最佳答案
是的,你可以。在 oracle 中,递归选择很容易。这是我的建议:
Update family set flag='Y'
where id in(select id from family start with id=3
connect by prior id=parent_id)
关于sql - 使用 Oracle sql 根据父值更新子行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27558223/