从查询中按顺序返回id

时间:2016-04-19 20:24:03

标签: sql oracle

说我有以下查询

SELECT * 
FROM foo 
WHERE P_KEY IN (5,7,2,6);

当我输入查询时,P_KEY值以2,5,6,7的顺序返回行。 我该怎么做才能按照我在IN子句中输入的顺序返回行

P_KEY
5
7
2
6

不是这个

P_KEY
2
5
6
7

2 个答案:

答案 0 :(得分:0)

您无法按IN子句中的项目顺序直接排序。您必须创建临时表或内联子查询以向值添加订单:

SELECT Foo.* FROM FOO
INNER  JOIN
(
   SELECT 5 AS [Key], 1 AS [Order]
   UNION ALL
   SELECT 7 AS [Key], 2 AS [Order]
   UNION ALL
   SELECT 2 AS [Key], 3 AS [Order]
   UNION ALL
   SELECT 6 AS [Key], 4 AS [Order]
) j
ON P_KEY = j.key
ORDER BY j.[Order]

答案 1 :(得分:0)

一个简单但不太优雅的解决方案是使用UNION

SELECT * FROM foo WHERE P_KEY =5
UNION
SELECT * FROM foo WHERE P_KEY =7
UNION
SELECT * FROM foo WHERE P_KEY =2
UNION
SELECT * FROM foo WHERE P_KEY =6