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');
2.使用order by field
select * from table where id in (922,106,104,103) order by field(id,922,106,104,103);
下面是在tp5中的實現過程
1 $path = '103-104-106-922'; 2 $arr = explode('-',$path); 3 dump($arr); 4 $new_arr = array_reverse($arr); 5 dump($new_arr); 6 $new_arr1 = implode(',',$new_arr); 7 dump($new_arr1); 8 $list = Db::name('member') 9 ->where('id','in',$new_arr1) 10 ->where('type',2) 11 ->field('id,type') 12 //->order("find_in_set(id,$new_arr1)")
13 ->order("field(id,$new_arr1)") 14 ->select(); 15 dump($list);die;
查詢結果如下所示,可見實現了按照where in 數組順序進行排序了
1 array(4) { 2 [0] => string(3) "103"
3 [1] => string(3) "104"
4 [2] => string(3) "106"
5 [3] => string(3) "922"
6 } 7 array(4) { 8 [0] => string(3) "922"
9 [1] => string(3) "106"
10 [2] => string(3) "104"
11 [3] => string(3) "103"
12 } 13 string(15) "922,106,104,103"
14 array(4) { 15 [0] => array(2) { 16 ["id"] => int(922) 17 ["type"] => int(2) 18 } 19 [1] => array(2) { 20 ["id"] => int(106) 21 ["type"] => int(2) 22 } 23 [2] => array(2) { 24 ["id"] => int(104) 25 ["type"] => int(2) 26 } 27 [3] => array(2) { 28 ["id"] => int(103) 29 ["type"] => int(2) 30 } 31 }