我有一个像这样的MySQL脚本:SELECT id, name FROM users WHERE id IN (6,4,34)
IN(...)数组中的序列非常重要。是否有可能按照给定的顺序得到它们?
答案 0 :(得分:9)
您可以使用MySQL FIELD
function来保持紧凑;
SELECT id, name
FROM users
WHERE id IN (6, 4, 34)
ORDER BY FIELD(id, 6, 4, 34);
答案 1 :(得分:3)
尝试
SELECT id, name FROM users WHERE id IN (6,4,34) order by FIELD(id,6,4,34)
答案 2 :(得分:1)
您可以使用ORDER BY子句中的任何表达式,包括'CASE':
ORDER BY CASE id
WHEN 6 THEN 1
WHEN 4 THEN 2
WHEN 34 THEN 3
END ASC
如果您的列表来自应用程序编程层,您可以使用以下内容(此处为PHP)构建它:
$sortVal = 1;
foreach($ids as $id_val) {
$cases[] = sprintf('WHEN %i THEN %i', $id_val, $sortVal++);
}
$order_by = 'ORDER BY CASE id ' . implode($cases) . ' END ASC';
但是,我会提到约阿希姆的答案非常优雅: - )
答案 3 :(得分:0)
基于 Chris Trahey 回答的完整示例。
$ids = array("table1", "table2", "table3");
$sortVal = 1;
foreach ($ids as $id_val) {
$cases[] = sprintf("WHEN '%s' THEN %u ", $id_val, $sortVal++);
}
$order_by = 'ORDER BY CASE `tableName` ' . implode($cases) . ' END ASC';
$result = mysqli_query( $con, "
SELECT DISTINCT tableName
FROM `table`
$order_by");