MySQL 使用 SELECT...WHERE id IN (...),按 IN() 排序结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2435986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:30:21  来源:igfitidea点击:

With a SELECT...WHERE id IN (...), order results by IN()?

sqlmysqlsql-order-by

提问by Jeff

Possible Duplicate:
Ordering by the order of values in a SQL IN() clause

可能的重复:
按 SQL IN() 子句中值的顺序排序

With a query such as:

使用查询,例如:

SELECT * FROM images WHERE id IN (12,9,15,3,1)

is it possible to order the results by the contents of the IN clause?

是否可以按 IN 子句的内容对结果进行排序?

The result I'm looking for would be something like:

我正在寻找的结果类似于:

[0] => Array
    (
        [id] => 12
        [file_name] => foo
    )   
[1] => Array
    (
        [id] => 9
        [file_name] => bar
    )   
[2] => Array
    (
        [id] => 15
        [file_name] => baz
    )
...

采纳答案by Daniel Vassallo

The INclause defines a set, and a set in mathematics has no order.

IN子句定义了一个集合,数学中的集合没有顺序。

However there seems to be a workaround for MySQL by using the FIELD()function:

但是,通过使用FIELD()函数,MySQL 似乎有一种解决方法: