MySQL MySQL按数组值排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8055138/
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 21:35:55  来源:igfitidea点击:

MySQL sort order by array value

mysqlarrayssortingsql-order-by

提问by Marty

I need to run a MySQL query where the order is determined by an array value.

我需要运行一个 MySQL 查询,其中的顺序由数组值确定。

My array is variable but the values in the array correspond to a field in my DB table called 'ID' so I want the result to be returned in the ID order 9, 1, 4.

我的数组是可变的,但数组中的值对应于我的数据库表中名为“ID”的字段,因此我希望以 ID 顺序 9、1、4 返回结果。

Array ( [0] => 9 [1] => 1 [2] => 4 )

Is this possible in MySQL or would it be possible to sort the MySQL $result using the array after? You can assume the only values being returned are those in the array.

这在 MySQL 中是可能的,还是可以使用数组对 MySQL $result 进行排序?您可以假设返回的唯一值是数组中的值。

回答by hari jee

You want to get a list of items with the ids 5, 2, 1, 3and output them in the same order. However, just running a select query will return the items in the order 1, 2, 3, 5.

您想要获取带有 id 的项目列表5, 2, 1, 3并以相同的顺序输出它们。但是,仅运行一个选择查询将返回 order 中的项目1, 2, 3, 5

To order the results correctly you need to build a list of ORDER BYitems describing the weights of the ids. This will look like

要正确排序结果,您需要构建一个ORDER BY描述 id 权重的项目列表。这看起来像

ORDER BY id = 5 DESC, id = 2 DESC, id = 1 DESC, id = 3 DESC