With a SELECT…WHERE id IN (…), order results by IN()? [duplicate]

泄露秘密 提交于 2020-01-23 04:23:23

问题


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

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?

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
    )
...

回答1:


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

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

  • Ordering by the order of values in a SQL IN() clause


来源:https://stackoverflow.com/questions/2435986/with-a-select-where-id-in-order-results-by-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!