MySQL获取记录按顺序传递给IN条件

时间:2013-10-31 10:48:24

标签: mysql sql

希望结果与传递给IN条件的顺序相同:

SELECT * FROM `table_x` WHERE `id` IN (30, 12, 1001, 24);

获得:

id    | field_a | field_b
--------------------------
12    | ...     | ...
24    | ...     | ...
30    | ...     | ...
1001  | ...     | ...

期待:

id    | field_a | field_b
--------------------------
30    | ...     | ...
12    | ...     | ...
1001  | ...     | ...
24    | ...     | ...

2 个答案:

答案 0 :(得分:2)

SELECT * FROM `table_x` 
WHERE `id` IN (30, 12, 1001, 24) 
order by field(id, 30, 12, 1001, 24)

答案 1 :(得分:1)

FIELD函数的

Reference

SQLFiddle

SELECT * 
  FROM `table_x` 
  WHERE `id` IN (30, 12, 1001, 24) 
  ORDER BY FIELD(id, 30, 12, 1001, 24);

您将获得输出

|   ID | FIELD_A | FIELD_B |
|------|---------|---------|
|   30 |     ... |     ... |
|   12 |     ... |     ... |
| 1001 |     ... |     ... |
|   24 |     ... |     ... |