MySQL - SELECT ... WHERE id IN (..) - 正确顺序

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

MySQL - SELECT ... WHERE id IN (..) - correct order

mysql

提问by Ciprian Mocanu

I have the following query

我有以下查询

SELECT * FROM table WHERE id IN (5,4,3,1,6)

and i want to retrieve the elements in the order specified in the "id in.." meaning it should return:

我想按照“id in..”中指定的顺序检索元素,这意味着它应该返回:

5 ....
4 ....
3 ....
1 ....
6 ....

Any ideas how to do that?

任何想法如何做到这一点?

回答by Frank Heikens

Use FIELD():

使用FIELD()

SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD(id, 5,4,3,1,6);

回答by delphist

SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD (id, 5,4,3,1,6)

回答by Ciprian Mocanu

In case anyone is still searching I just found it..

万一有人还在搜索我刚刚找到它..

SELECT * FROM `table` WHERE `id` IN (4, 3, 1) ORDER BY FIELD(`id`, 4, 3, 1)

And a reference for the function you can find HERE

您可以在此处找到该功能的参考

回答by Robbie Tapping

Well your going to have to create a Id for each of the id's so:

那么你将不得不为每个 id 创建一个 Id,所以:

id | otherid

身 | 其他

1 = 5 2 = 4 3 = 3 4 = 1 6 = 6

1 = 5 2 = 4 3 = 3 4 = 1 6 = 6

using the IN STATEMENT only looks to see if those values are in the List, doesnt order them in any specific order

使用 IN STATEMENT 仅查看这些值是否在 List 中,不会以任何特定顺序对它们进行排序