【问题标题】:Does Oracle allow an ORDER BY within an IN clause?Oracle 是否允许在 IN 子句中使用 ORDER BY?
【发布时间】:2008-10-29 19:12:16
【问题描述】:

当我运行这个查询时,Oracle 给我一个错误(ORA-00907:缺少右括号):

select * 
from reason_for_appointment 
where reason_for_appointment_id in 
(
    select reason_for_appointment_id 
    from appointment_reason 
    where appointment_id = 11 
    order by appointment_reason_id
)

但是,当我只运行子查询时,没有错误。

谁能解释一下问题出在哪里?

【问题讨论】:

  • 您这样做的原因是什么?排序应该是不必要的操作,因为 Oracle 索引将在幕后执行此操作。
  • 什么?在幕后做什么?为什么它会对索引做任何事情?

标签: oracle plsql ora-00907


【解决方案1】:

内部查询结果永远不会显示,因此在嵌套选择中进行排序是没有意义的。而是将其应用于外部查询。

【讨论】:

    【解决方案2】:

    问题是在这样的子查询中不允许使用 ORDER BY。你为什么想要一个?

    【讨论】:

    • 我猜他想要按 ID 字段排序的输出。请参阅我的答案以了解如何做到这一点。
    【解决方案3】:

    您似乎希望使用在另一个表中定义的顺序来显示一个表中的结果。内连接就足够了。

    select reason_for_appointment.*
    from reason_for_appointment rfa, appointment_reason ar
    where rfa.reason_for_appointment_id = ar.reason_for_appointment_id
    and ar.appointment_id = 11
    order by ar.appointment_reason_id;
    

    【讨论】:

    • 不,这并不总是正确的。 IN 可以重铸为连接 IF AND ONLY IF IN 子句中的列具有唯一约束。如果在约会原因中有 27 行的 reason_for_appointment_id 为“1”,您将在结果中获得 27 行,但只有 1 行带有 IN。你们吓到我了。
    【解决方案4】:

    select * from reason_for_appointment where reason_for_appointment_id in(select reason_for_appointment_id fromointment_reason whereointment_id = 11 order by modify_reason_id)

    尝试类似: 辅助为(从约会原因中选择reason_for_appointment_id,其中约会id = 11,按约会原因id排序) select reason_for_appointment_id fromointment_reason where reason_for_appointment_id in(select reason_for_appointment_id from auxiliar)

    【讨论】:

      【解决方案5】:

      如果您的目标是对输出进行排序,您只需将 ORDER BY 移到子查询之外:

      select * from reason_for_appointment where reason_for_appointment_id in
       (select reason_for_appointment_id from appointment_reason where appointment_id = 11)
       order by reason_for_appointment_id
      

      (我假设你写“appointment_reason_id”的地方是“reason_for_appointment_id”。如果真的有两个不同的列具有这些名称......哎呀。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-12
        • 2016-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-15
        • 2014-02-21
        相关资源
        最近更新 更多