mysql中自定义排序_mysql自定义排序

bd96500e110b49cbb3cd949968f18be7.png

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 maintain the order (2,4,1,5,3) without changing the database structure?

Thanks!

解决方案

i ask this :

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 :

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

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值