MySQL mysql按固定列表排序

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

mysql order by a fixed list

mysqlsql

提问by timpone

I am going to have a fixed list of items to order by that I won't know until I run the query since there is a randomization step.

我将有一个固定的项目列表来订购,直到我运行查询时我才会知道,因为有一个随机化步骤。

I would like to have something like the following:

我想要以下内容:

assume that is_launch_set will return 1,3,7,11 but have been randomized to below:

假设 is_launch_set 将返回 1,3,7,11 但已随机分配到以下:

select * from items where is_launch_set=1 order by id values (3,11,7,1);

any ideas on how to achieve this? I was thinking maybe a find_in_set but not really sure.

关于如何实现这一目标的任何想法?我在想也许是 find_in_set 但不太确定。

回答by zerkms

You can do that by using either:

您可以使用以下任一方法来做到这一点:

ORDER BY FIND_IN_SET(id, '3,11,7,1')

or

或者

ORDER BY FIELD(id, 3, 11, 7, 1)

or

或者

ORDER BY CASE id WHEN 3 THEN 0
                WHEN 11 THEN 1
                 WHEN 7 THEN 2
                 WHEN 1 THEN 3
                        ELSE 4
         END