mysql custom sort

前端 未结 4 1791
遥遥无期
遥遥无期 2020-12-01 09:32

I have a query like this: SELECT * FROM table WHERE id IN (2,4,1,5,3);

However, when I print it out, it\'s automatically sorted 1,2,3,4,5. How can we ma

4条回答
  •  悲哀的现实
    2020-12-01 10:23

    i ask this :

    mysql order by issue

    the answers that i get and all the credit belong to them is :

    You can use a CASE operator to specify the order:

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

    in php u can do it like :

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

提交回复
热议问题