Home  >  Article  >  Backend Development  >  为什么MySQL的in查询会自动排序

为什么MySQL的in查询会自动排序

WBOY
WBOYOriginal
2016-06-06 20:43:271132browse

<code class="lang-php">$id_arr = array(2,6,3,10);//排好序的id列表
$sql = "select user,id from user_member where id in (".implode(",",$id_arr).")";

</code>

本来对id排序好了,结果查出来sql会自动对id再排序,怎么能按$id_arr的顺序显示呢?

回复内容:

<code class="lang-php">$id_arr = array(2,6,3,10);//排好序的id列表
$sql = "select user,id from user_member where id in (".implode(",",$id_arr).")";

</code>

本来对id排序好了,结果查出来sql会自动对id再排序,怎么能按$id_arr的顺序显示呢?

order by null

数据库 不会按你想的那样来做. 数据库自己的标准, 怎样使查询更有效率.
在这里, 要么全表扫一遍(或覆盖索引), 要么按索引查询.

要得到你的结果, 要么在sql里做一些比较tricky的事情, 要么放在你的php里排序.

<code>select user, id
from 
 (select user,id, field(id, 2,6,3,10) row 
   from user_member 
   where id in (2,6,3,10)) TMP
order by row;
</code>

WHERE id IN($id) ORDER BY find_in_set(id ,'{$id}')

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn