我想按IN条件传递顺序获取记录。
从表中选择*,其中id为(6,3,7,1); 将行返回为
id name
1 abc
3 xy
6 ab
7 ac
但是我希望以与Oracle中的条件传递的ID相同的顺序显示记录
id name
6 ab
3 xy
7 ac
1 abc
请帮助我以与oracle中的条件ID相同的顺序获取记录。 IN条件中的值可能会动态变化。
答案 0 :(得分:1)
您可以使用case
子句中的order by
语句或使用join
来执行此操作。
select *
from table
where id in(6,3,7,1)
order by (case id when 6 then 1 when 3 then 2 when 7 then 3 when 1 then 4 end);
或者:
with ids as (
select 6 as id, 1 as ordering from dual union all
select 3 as id, 2 as ordering from dual union all
select 7 as id, 3 as ordering from dual union all
select 1 as id, 4 as ordering from dual
)
select *
from table t join
ids
on t.ids = ids.id
order by ids.ordering;
请注意,在这种情况下,您不需要in
,因为join
会进行过滤。
答案 1 :(得分:0)
你可以使用技巧
select * from table where id in(6,3,7,1) order by case when id = 6 then 1
id = 3 then 2
id = 7 then 3
id = 1 then 4
end