CREATE TABLE users (
id INT,
name TEXT
);
INSERT INTO users VALUES
(1, "John"),
(2, "Susan"),
(3, "Timothy"),
(4, "Robert"),
(5, "Jim"),
(6, "Patricia");
$var = $db->prepare("
SELECT name
FROM users
WHERE id IN (3, 2, 4, 6)
");
$var->execute();
这将返回表中id
出现顺序的结果,即“2,3,4,6”。有没有办法按照WHERE ... IN
子句中指定的顺序对此进行排序?
预期结果将是:
+----+
| id |
+----+
| 3 |
| 2 |
| 4 |
| 6 |
+----+
答案 0 :(得分:4)
您需要order by
才能完成任务。一种方法是使用field()
:
SELECT name
FROM users
WHERE id IN (3, 2, 4, 6)
ORDER BY field(id, 3, 2, 4, 6);
答案 1 :(得分:2)
SELECT name
FROM users
WHERE id IN (3, 2, 4, 6)
order by find_in_set(id, '3,2,4,6')