1
2
3
4
5
6
7
8
9
10
mysql> select * from auth_permission where id in (23, 4,12, 4,1);
+----+----------------------------+-----------------+-----------------------+
| id | name | content_type_id | codename |
+----+----------------------------+-----------------+-----------------------+
| 1 | Can add bookmark | 1 | add_bookmark |
| 4 | Can add pinned application | 2 | add_pinnedapplication |
| 12 | Can delete permission | 4 | delete_permission |
| 23 | Can change session | 8 | change_session |
+----+----------------------------+-----------------+-----------------------+
4 rows in set (0.00 sec)

默认in查询结果集都会使用id排序

1. 使用field函数

FIELD(str,str1,str2,str3,…)
Returns the index (position) of str in the str1, str2, str3, … list. Returns 0 if str is not found.

1
2
3
4
5
6
7
8
9
10
mysql> select * from auth_permission where id in (23, 4,12, 4,1) order by field(id,23,4,12,4,1);
+----+----------------------------+-----------------+-----------------------+
| id | name | content_type_id | codename |
+----+----------------------------+-----------------+-----------------------+
| 23 | Can change session | 8 | change_session |
| 4 | Can add pinned application | 2 | add_pinnedapplication |
| 12 | Can delete permission | 4 | delete_permission |
| 1 | Can add bookmark | 1 | add_bookmark |
+----+----------------------------+-----------------+-----------------------+
4 rows in set (0.00 sec)

2. 使用关联查询