使用WHERE IN子句按顺序获取行

时间:2017-06-16 16:54:05

标签: mysql sql

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 |
+----+

2 个答案:

答案 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')