SQL - 按 id 列表部分排序

SQL - partially order by list of id's

我有一个要查询的 table,条件类似于 id >10,我想根据列表中的 ID 添加一个条件,例如 AND id IN(3,4,5,6,7)

我想先按列表中的 ID 对结果进行排序。 可以吗?

如果您使用 MySQL:(请适当标记问题)

来自manual

FIELD(str,str1,str2,str3,...)

Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

If all arguments to FIELD() are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double.

If str is NULL, the return value is 0 because NULL fails equality comparison with any value. FIELD() is the complement of ELT().

mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 2
mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 0

所以你可以轻松做到

SELECT
...
ORDER BY FIELD(id, 3,4,5,6,7), id