我在 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更新sql,不仅用flight更新相应的父行并将标志更改为Y,而且子行也应该相应更新。如果航班表中没有相应的家庭航班分配,则第 6,7 行应保留原样。
轻松进行父级更新并为父级查找子级。但是是否可以在一条 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)
在 Oracle 中更新所有系列(而不仅仅是特定系列)的另一种方法可能是:
update family F
set flag='Y',
FLIGHT=(
SELECT FLIGHT FROM FLIGHT WHERE FAMILY_ID=F.PARENT_ID OR f.id=family_id
)
WHERE ID IN (select id
from family a
start with id in (
select family_id from flight where a.id=family_id)
connect by prior id=parent_id);
希望有帮助。