mysql按问题排序 [英] mysql order by issue

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

问题描述

如果我有类似的查询:

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

这个id数组是动态地在php中构建的, 订单对我来说很重要.

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 ?

有可能在MYSQL查询中做到这一点, 还是我必须通过php订购它?

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

推荐答案

您可以按从列派生的值进行排序.您可以使用 CASE 运算符来指定顺序:

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

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

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