MySQL查询时,查询结果如何按照where in数组排序

MySQL查询时,查询结果如何按照where in数组排序

在查询中,MySQL默认是order by id asc排序的,但有时候需要按照where in 的数组顺序排序,比如where in的id查询数组为[922,106,104,103],正常情况查询出来的结果顺序为[103,104,106,922],这可能不是我们想要的结果,

我们期望查出来的结果顺序与where in的顺序一致,这里介绍两个方式:

  1. 使用find_in_set函数:
    select * from table where id in (922,106,104,103) order by
    find_in_set(id,'922,106,104,103');
  1. 使用order by field
    select * from table where id in (922,106,104,103) order by
    field(id,922,106,104,103);

下面是在tp5中的实现过程

$path = '103-104-106-922';
$arr = explode('-',$path);
dump($arr);
$new_arr = array_reverse($arr);
dump($new_arr);
$new_arr1 = implode(',',$new_arr);
dump($new_arr1);
$list = Db::name('member')
    ->where('id','in',$new_arr1)
    ->where('type',2)
    ->field('id,type')
    //->order("find_in_set(id,$new_arr1)")
    ->order("field(id,$new_arr1)")
    ->select();
dump($list);die;

查询结果如下所示,可见实现了按照where in 数组顺序进行排序了

array(4) {
  [0] => string(3) "103"
  [1] => string(3) "104"
  [2] => string(3) "106"
  [3] => string(3) "922"
}
array(4) {
  [0] => string(3) "922"
  [1] => string(3) "106"
  [2] => string(3) "104"
  [3] => string(3) "103"
}
string(15) "922,106,104,103"
array(4) {
  [0] => array(2) {
    ["id"] => int(922)
    ["type"] => int(2)
  }
  [1] => array(2) {
    ["id"] => int(106)
    ["type"] => int(2)
  }
  [2] => array(2) {
    ["id"] => int(104)
    ["type"] => int(2)
  }
  [3] => array(2) {
    ["id"] => int(103)
    ["type"] => int(2)
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章