5

我有一个这样的 MySQL 脚本:SELECT id, name FROM users WHERE id IN (6,4,34)

IN(...) 数组中的序列非常重要。是否可以按照给定的顺序获取它们?

4

4 回答 4

13

您可以使用MySQLFIELD功能使其保持紧凑;

SELECT id, name 
FROM users 
WHERE id IN (6, 4, 34)
ORDER BY FIELD(id, 6, 4, 34);
于 2013-02-17T17:10:27.547 回答
3

尝试

SELECT id, name FROM users WHERE id IN (6,4,34) order by FIELD(id,6,4,34)
于 2013-02-17T17:11:04.363 回答
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';

但是,我会提到约阿希姆的回答非常优雅:-)

于 2013-02-17T17:05:19.803 回答
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");
于 2021-01-28T20:36:35.567 回答