sql - 使用 Oracle sql 根据父值更新子行

标签 sql oracle parent-child hierarchy

我在 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/

相关文章:

java - 颠倒的问号问题

java - 通过 JDBC 驱动程序连接到 Oracle 数据库

hibernate - Grails GORM-在 parent 之前救助 child

MYSQL Where on DateTime 错误结果

sql - Oracle 分配给 "count(*)"的 SQL 数据类型是什么?

sql - 如何为递归sql设置停止条件?

ios - 从子 VC 动画父 VC 对象

mysql - 如何使用地址或电话号码关联 parent /子女关系中的帐户?

使用 Spring JDBC 执行 SQL 函数

sql - 如何在 PostgreSQL 中从右边抓取