mysql order by issue

前端 未结 5 1078
后悔当初
后悔当初 2021-01-06 09:57

if i have a query like :

SELECT * FROM table  WHERE id IN (3,6,1,8,9);

this array of the ids is build in php dynamically , and the order is

5条回答
  •  忘掉有多难
    2021-01-06 10:37

    I haven't tested but this PHP solution should work:

     $v){
        $sql .= 'WHEN ' . $v . ' THEN ' . $k . "\n";
    }
    $sql .= 'END ';
    
    echo $sql;
    
    ?>
    

    This generates the following SQL code:

    SELECT * FROM table  WHERE id IN (3,6,1,8,9)
    ORDER BY CASE id
    WHEN 3 THEN 0
    WHEN 6 THEN 1
    WHEN 1 THEN 2
    WHEN 8 THEN 3
    WHEN 9 THEN 4
    END
    

提交回复
热议问题