【问题标题】:How to update rows from a recursive result?如何从递归结果更新行?
【发布时间】:2023-03-17 00:44:01
【问题描述】:

我有一个表示简单目录结构的表(set_idparent_id -> set_id)。现在在我的应用程序中,当我更新目录时,我希望树中的所有父级递归更新。我试过了

with recursive parents as (
    select *
    from sets
    where set_id=$1

    union all

    select s.*
    from sets s
    join parents p on p.parent_id=s.set_id
)
update parents
set updated=now();

但是我有一个错误,说子表不存在。我觉得我太累了,现在看不到其他路了,有人可以帮忙吗?

谢谢

【问题讨论】:

    标签: sql database postgresql recursion sql-update


    【解决方案1】:

    你需要加入update中的表:

    with recursive parents as (
        select * from sets where set_id=$1
        union all
        select s.* from sets s join parents p on p.parent_id=s.set_id
    )
    update sets s
    set updated = now()
    from parents p
    where p.id = s.id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 2011-06-18
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多