MySQL查詢時,查詢結果如何按照where in數組排序
在查詢中,MySQL默認是order by id asc排序的,但有時候需要按照where in 的數組順序排序,比如where in的id查詢數組爲[922,106,104,103],正常情況查詢出來的結果順序爲[103,104,106,922],這可能不是我們想要的結果,
我們期望查出來的結果順序與where in的順序一致,這裏介紹兩個方式:
- 使用find_in_set函數:
select * from table where id in (922,106,104,103) order by
find_in_set(id,'922,106,104,103');
- 使用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)
}
}