mysql自定义排序 [英] mysql custom sort

查看:157
本文介绍了mysql自定义排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的查询:SELECT * FROM table WHERE id IN (2,4,1,5,3);

但是,当我打印出来时,它会自动进行1,2,3,4,5的排序.如何在不更改数据库结构的情况下保持顺序(2,4,1,5,3)?

However, when I print it out, it's automatically sorted 1,2,3,4,5. How can we maintain the order (2,4,1,5,3) without changing the database structure?

谢谢!

推荐答案

我问这个问题:

mysql发行问题

我得到的答案和所有功劳归于他们:

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

您可以使用CASE运算符指定顺序:

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

在php中,您可以这样做:

in php u can do it like :

<?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;

?>

这篇关于mysql自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆