select HId, TestM, *
from TestDb
where Hid in ( 4, 5, 7, 9, 1, 132, 312)
如果我运行上面的.sql文件,默认情况下第一列将按升序排序。
我确实希望Hid列按照where子句中的值的顺序排列。我怎样才能做到这一点?
Hid | TestM | ...
_______________
4
5
7
9
1
132
312
答案 0 :(得分:6)
您必须在ORDER BY
子句中使用SELECT HId, TestM, *
FROM TestDb
WHEN Hid IN ( 4, 5, 7, 9, 1, 132, 312)
ORDER BY CASE Hid
WHEN 4 THEN 1
WHEN 5 THEN 2
WHEN 7 THEN 3
WHEN 9 THEN 4
WHEN 1 THEN 5
WHEN 132 THEN 6
WHEN 312 THEN 7
END
表达式:
ORDER BY
另请注意,表格只是无序集合,因此如果您将 <dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m10</version>
</dependency>
子句保留,则无法保证结果集的顺序。
答案 1 :(得分:1)
SQL没有隐式排序。如果没有声明ORDER BY
,则结果可以按任何顺序返回,并且每次对相同数据执行相同查询时可能会返回不同的顺序。
常用的方法是使用CASE语句,但这可能变得笨重...
ORDER BY
CASE HId WHEN 4 THEN 1
WHEN 5 THEN 2
WHEN 7 THEN 3
WHEN 8 THEN 4
WHEN 1 THEN 5
WHEN 123 THEN 6
WHEN 312 THEN 7 END
另一种方法是在一个表上加入JOIN,该表包含要过滤的值和要排序的列。它的笨拙,关系性更强,更容易扩展......
SELECT
TestDB.HId, TestDB.TestM, TestDB.*
FROM
TestDB
INNER JOIN
(
SELECT 4 AS val, 1 AS ordinal
UNION ALL SELECT 5 AS val, 2 AS ordinal
UNION ALL SELECT 7 AS val, 3 AS ordinal
UNION ALL SELECT 8 AS val, 4 AS ordinal
UNION ALL SELECT 1 AS val, 5 AS ordinal
UNION ALL SELECT 132 AS val, 6 AS ordinal
UNION ALL SELECT 312 AS val, 7 AS ordinal
)
filter
ON filter.value = TestDB.HId
ORDER BY
filter.ordinal