How to display records from a table ordered as in the where clause?

好久不见. 提交于 2020-01-11 11:27:10

问题


I am trying to display the records,order as in the where clause.. example:

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

It displays Arun,Naveen,Yaksha (alphabetical order)
I want display it as same order i.e 'Yaksha''Arun','Naveen'
how to display this... I am using oracle db.


回答1:


Add this ORDER BY at the query's end:

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

(There's no other way to get that order. You need an ORDER BY to get a specific result set order.)




回答2:


It may be a bit clunky, but you can create a custom ordering with a case expression:

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

A slightly longer option, but one that prevents duplication of the string literals is to use a subquery:

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



回答3:


You can try with something like the following:

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

This way could be useful if your IN list is somehow dynamic.




回答4:


If the list of values is dynamic or you just don't want to repeat the values you could use (or abuse, depending on your point of view) a table collection, and join your real table to a table collection expression instead of using IN:

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

Which will generally work, but of course without an order-by clause is not guaranteed to work, so you can use an inline view to assign the order:

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;

This still relies on row_number() over (order by null) using the order of the elements in the collection; which relies on collection unnesting preserving the element order. I don't think that's guaranteed either, so there is still some risk involved.



来源:https://stackoverflow.com/questions/35361718/how-to-display-records-from-a-table-ordered-as-in-the-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!