我有以下查询
SELECT * FROM table WHERE id IN (5,4,3,1,6)
我希望按照“id in ..”中指定的顺序检索元素,这意味着它应该返回:
5 ....
4 ....
3 ....
1 ....
6 ....
任何想法如何做到这一点?
答案 0 :(得分:51)
使用FIELD():
SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD(id, 5,4,3,1,6);
答案 1 :(得分:24)
SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD (id, 5,4,3,1,6)
答案 2 :(得分:2)
如果有人还在搜索我刚刚找到它..
SELECT * FROM `table` WHERE `id` IN (4, 3, 1) ORDER BY FIELD(`id`, 4, 3, 1)
您可以找到HERE
的功能参考答案 3 :(得分:-1)
那么你必须为每个id创建一个Id:
id | otherid
1 = 5 2 = 4 3 = 3 4 = 1 6 = 6
使用IN STATEMENT只查看这些值是否在列表中,不按任何特定顺序排序