一尘不染

Oracle SQL命令在子查询中的问题!

sql

我试图在Oracle SQL中运行子查询,但不会让我订购子查询列。排序子查询很重要,因为Oracle似乎可以随意选择返回的哪些列返回主查询。

``

select ps.id, ps.created_date, pst.last_updated, pst.from_state, pst.to_state,
        (select last_updated from mwcrm.process_state_transition subpst
            where subpst.last_updated > pst.last_updated
            and subpst.process_state = ps.id
            and rownum = 1) as next_response
        from mwcrm.process_state ps, mwcrm.process_state_transition pst
        where ps.created_date > sysdate - 1/24
        and ps.id=pst.process_state
        order by ps.id asc

确实应该是:

``

select ps.id, ps.created_date, pst.last_updated, pst.from_state, pst.to_state,
        (select last_updated from mwcrm.process_state_transition subpst
            where subpst.last_updated > pst.last_updated
            and subpst.process_state = ps.id
            and rownum = 1
            order by subpst.last_updated asc) as next_response
        from mwcrm.process_state ps, mwcrm.process_state_transition pst
        where ps.created_date > sysdate - 1/24
        and ps.id=pst.process_state
        order by ps.id asc

阅读 139

收藏
2021-03-17

共1个答案

一尘不染

实际上,“排序”仅在最外部的查询中有意义-如果您在子查询中进行排序,则允许外部查询随意对结果进行加扰,因此子查询的排序实际上不执行任何操作。

看起来您只想获取大于pst.last_updated的最小last_updated-
当您将其视为最小值(总计)而不是第一行(而不是第一行)时,这样做会更容易(这会带来其他问题,例如有两行用于next_response?)

试一试。合理的警告,自从我开始使用Oracle已有数年了,而且我不习惯使用subquery-as-a-
column语法;如果爆炸了,我将在from子句中对其进行版本化。

select
    ps.id, ps.created_date, pst.last_updated, pst.from_state, pst.to_state,
    (   select min(last_updated)
        from mwcrm.process_state_transition subpst
        where subpst.last_updated > pst.last_updated
          and subpst.process_state = ps.id) as next_response
from <the rest>
2021-03-17