【问题标题】:update using nested queries in oracle sql-developer在 oracle sql-developer 中使用嵌套查询进行更新
【发布时间】:2021-03-09 13:52:44
【问题描述】:

我在 nltl 表中有 3 条记录,它们都有不同的locked_dt => 锁定日期。现在我想更新其中的 is_locked 标志,以获取位于最后位置(最旧日期)的记录,即第三级。内部子查询工作正常,但子查询连同更新语句出现问题(SQL 命令未正确结束)

nltl 表:{ l_id、c_id、e_id、t_id、ee_id、locked_dt、is_locked }

update nltl set is_locked = 0
from (
        select t_id, l_id, e_id, ee_id, c_id, is_locked from (
        select ppl.*, DENSE_RANK() over (order by ppl.locked_dt desc) my_rnk
        from nltl ppl
        where ppl.l_d = 17 and ppl.t_id = 55 and ppl.c_id = 3 and ppl.e_id = 1509919001 and ppl.ee_id = 15099190
        ) t where my_rnk = 3
    )
    
where t_id = t.t_id, l_id = t.l_id, e_id = t.e_id, ee_id = t.ee_id, c_id = t.c_id;

【问题讨论】:

  • 在 from 之后起一个名字:update nltl set is_locked=0 from (...) x 并且不需要在子查询中选择is_locked
  • 你检查UPDATE语句的语法了吗? FROM没有位置

标签: sql oracle


【解决方案1】:

您需要为此使用MERGE 语句,因为Oracle 不支持以表为源的UPDATE 语句。但只要你的新值不依赖于任何计算值,这可以通过简单的IN 谓词来完成:

update nltl t
set is_locked = 0
where (l_id, c_id, e_id, t_id, ee_id, locked_dt) in (
  select ppl.l_id, ppl.c_id, ppl.e_id, ppl.t_id, ppl.ee_id, ppl.locked_dt
  from (
    select
      ppl.*,
      dense_rank() over (order by ppl.locked_dt desc) my_rnk
    from nltl ppl
    where
      ppl.l_d = 17
      and ppl.t_id = 55
      and ppl.c_id = 3
      and ppl.e_id = 1509919001
      and ppl.ee_id = 15099190
  )
  where my_rnk = 3
)

或者使用物理行地址来做没有索引或全表扫描:

update nltl t
set is_locked = 0
where rowid in (
  select rid
  from (
    select
      ppl.rowid as rid,
      dense_rank() over (order by ppl.locked_dt desc) my_rnk
    from nltl ppl
    where
      ppl.l_d = 17
      and ppl.t_id = 55
      and ppl.c_id = 3
      and ppl.e_id = 1509919001
      and ppl.ee_id = 15099190
  )
  where my_rnk = 3
)

【讨论】:

  • 我能以某种方式与您联系吗?我对此@astentx 有另一个疑问
【解决方案2】:

您可以按如下方式使用合并:

Merge into nltl t
Using (select t_id, l_id, e_id, ee_id, c_id from (
        select ppl.*, DENSE_RANK() over (order by ppl.locked_dt desc) my_rnk
        from nltl ppl
        where ppl.l_d = 17 and ppl.t_id = 55 and ppl.c_id = 3 and ppl.e_id = 1509919001 and ppl.ee_id = 15099190
        ) t where my_rnk = 3) s
On (s.t_id = t.t_id 
   And s.l_id = t.l_id
   And s.e_id = t.e_id
   And s.ee_id = t.ee_id
   And s.c_id = t.c_id)
When matched then 
  Update set t.is_locked=0

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2013-06-20
    • 2012-08-29
    • 2011-10-07
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2019-02-28
    • 2022-09-28
    相关资源
    最近更新 更多