如何显示在where子句中排序的表中的记录?

时间:2016-02-12 11:41:16

标签: sql oracle select sql-order-by where-clause

我正在尝试显示记录,在where子句中按顺序显示.. 例如:

select name from table where name in ('Yaksha','Arun','Naveen');

显示Arun,Naveen,Yaksha (alphabetical order)
我希望将其显示为相同的订单i.e 'Yaksha''Arun','Naveen'
如何显示这个...... 我正在使用oracle db。

4 个答案:

答案 0 :(得分:4)

在查询结尾处添加此ORDER BY

order by case name when 'Yaksha' then 1
                   when 'Arun'   then 2
                   when 'Naveen' then 3
         end

(没有其他方法可以获得该订单。您需要ORDER BY才能获得特定的结果集订单。)

答案 1 :(得分:2)

可能有点笨拙,但您可以使用case表达式创建自定义排序:

SELECT   *
FROM     my_table
WHERE    name IN ('Yaksha', 'Arun','Naveen')
ORDER BY CASE name WHEN 'Yaksha' THEN 1
                   WHEN 'Arun'   THEN 2
                   WHEN 'Naveen' THEN 3
         END ASC

稍长的选项,但防止字符串文字重复的选项是使用子查询:

SELECT   m.*
FROM     my_table m
JOIN     (SELECT 'Yaksha' AS name, 1 AS name_order FROM dual
          UNION ALL
          SELECT 'Arun' AS name, 2 AS name_order FROM dual
          UNION ALL
          SELECT 'Naveen' AS name, 3 AS name_order FROM dual) o 
         ON o.name = m.name
ORDER BY o.name_order ASC

答案 2 :(得分:2)

您可以尝试使用以下内容:

SELECT   *
FROM     test
WHERE    name IN (  'Yaksha', 'Arun', 'Naveen'  )
ORDER BY instr ( q'['Yaksha', 'Arun', 'Naveen']', name ) ASC

如果您的IN列表以某种方式动态,这种方式可能很有用。

答案 3 :(得分:2)

如果值列表是动态的,或者您只是不想重复使用(或滥用,取决于您的观点)表集合的值,并将您的真实表格加入{{3}而不是使用IN

select your_table.name
from table(sys.odcivarchar2list('Yaksha','Arun','Naveen')) t
join your_table on your_table.name = t.column_value;

通常可以使用,但当然没有order-by子句保证无法正常工作,因此您可以使用内联视图来分配订单:

select your_table.name from (
  select row_number() over (order by null) as rn, column_value as name
  from table(sys.odcivarchar2list('Yaksha','Arun','Naveen'))
) t
join your_table on your_table.name = t.name
order by t.rn;

这依赖于row_number() over (order by null)使用集合中元素的顺序;它依赖于集合而不需要保留元素顺序。我认为这也不保证,所以仍然存在一些风险。