mysql order by issue

情到浓时终转凉″ 提交于 2019-11-30 17:33:34

问题


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 important to me.

$my_array =  array (3,6,1,8,9) ;

how can i sort the results by the order by which the elements appear in my array ?

its possible to do it in MYSQL query, or i must to order it after via php ?


回答1:


You can order by a value derived from a column. 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



回答2:


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

<?php

$my_array =  array (3,6,1,8,9) ;

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

$sql .= "\nORDER BY CASE id\n";
foreach($my_array as $k => $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



回答3:


If you must do it this way you'll have to manipulate the data in PHP. MySQL can only order by natural orderings ascending or descending.

Got to question though - why do you need the data returned in this very specific order? There may be an easier solution to your problem by re-jigging something further up in the code.




回答4:


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



回答5:


You can load the results into an array with IDs as indexes:

 while ($row = mysql_fetch_array($l)) $items[$row['id']] = $row;

and then simply iterate it in your order

 foreach ($my_array as $id) { $current_row = $items[$id]; ... }


来源:https://stackoverflow.com/questions/2005350/mysql-order-by-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!