【问题标题】:Replace TOP 1 in H2 SQL that it works with Oracle替换与 Oracle 一起使用的 H2 SQL 中的 TOP 1
【发布时间】:2016-01-02 03:41:38
【问题描述】:

我有这个用于 H2 数据库的 SQL:

update EVENT event
set event.SENT_INTO_WF_BY_ID = (
  select TOP 1 eventRev.USER_ID
  from EVENT_REV eventRev
  where eventRev.EVENT_ID = event.EVENT_ID
  and eventRev.STATUS != (
    select TOP 1 eventRev2.STATUS
    from EVENT_REV eventRev2
    where VALID_FROM is not null
    and eventRev.EVENT_ID = eventRev2.EVENT_ID
    order by VALID_FROM asc
  )
  order by eventRev.VALID_TO asc nulls last
)
where event.SENT_INTO_WF_BY_ID is null

我必须翻译它以使其适用于 Oracle。在 Oracle 中,“TOP”不存在,所以我尝试了这个:

update EVENT event
set event.SENT_INTO_WF_BY_ID = (
  select eventRev.USER_ID
  from ( select eventRev.USER_ID from EVENT_REV eventRev
         where eventRev.EVENT_ID = event.EVENT_ID
         order by eventRev.VALID_TO asc nulls last )
  where rownum = 1

)
where event.SENT_INTO_WF_BY_ID is null;

但这给了我错误:

错误:ORA-00904:“事件”。“EVENT_ID”:无效标识符

有没有更多嵌套选择的解决方案?

【问题讨论】:

    标签: sql oracle nested translate


    【解决方案1】:

    您可以使用merge,但有一种方法可以使用update 解决此问题。那就是使用keep 功能:

    update EVENT e
        set e.SENT_INTO_WF_BY_ID = 
              (select max(er.USER_ID) keep (dense_rank first order by er.VALID_TO asc nulls last)
               from EVENT_REV er
               where er.EVENT_ID = e.EVENT_ID
              )
        where e.SENT_INTO_WF_BY_ID is null;
    

    您遇到的问题是由于 Oracle 中的范围规则。 Oracle 只识别来自外部查询的别名,深一级。

    【讨论】:

    • 像魅力一样工作!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2019-12-19
    相关资源
    最近更新 更多