【问题标题】:Get the results sorted in the same order as values inside the in() field of select获取按与 select 的 in() 字段中的值相同的顺序排序的结果
【发布时间】:2012-03-30 11:43:46
【问题描述】:

有没有办法按 IN() 子句中的值顺序排序? 我有一个选择查询:

Select * from abc where xyz in (a list of values).

我希望结果的排序顺序与括号内的列表相同。

一种方法是我可以将值放在一个具有递增序列的临时表中,然后将这两个表连接起来,然后按序列排序,但这不是一个好方法。

有没有办法做到这一点?

【问题讨论】:

    标签: oracle sorting sql-order-by


    【解决方案1】:

    不需要临时表(但也不是很漂亮)

    with list_values (seqnr, id) as (
        select 1, 42 from dual
        union all
        select 2, 43 from dual
        union all
        select 3, 44 from dual
        -- you get the picture
    )
    select *
    from abc
      join list_values lv on abc.xyz = lv.id
    order by lv.seqnr
    

    【讨论】:

    • 你的“不是很漂亮”,我的很“丑”……在这里感觉到一种模式;)
    • @Anonymous:解码解决方案也是一个“不错”的想法。没想到那个
    【解决方案2】:

    一个丑陋的选择是使用解码:

    Select * from abc 
    WHERE xyz in (a list of values) 
    ORDER BY DECODE(xyz, 'val1', 1, 'val2', 2, ...) 
    

    【讨论】:

      【解决方案3】:

      感谢您的所有回答。 还有一种做法,类似于a_horse_with_no_name的做法:

      with t as 
      (select t.*, rownum r from table (sys.odcinumberlist(val1, val2, val3...)) t)
      select * from abc ac, t where ac.id = column_value and is_active = 'Y' order by r
      

      这也应该有效。你们认为哪一种是最好和最佳的方法?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-27
        • 2011-03-22
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        相关资源
        最近更新 更多