avoid Sorting by the MYSQL IN Keyword

后端 未结 4 515
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 14:34

When querying the db for a set of ids, mysql doesnot provide the results in the order by which the ids were specified. The query i am using is the following:



        
4条回答
  •  别那么骄傲
    2020-12-19 15:26

    The behaviour you are seeing is a result of query optimisation, I expect that you have an index on id so that the IN statement will use the index to return records in the most efficient way. As an ORDER BY statement has not been specified the database will assume that the order of the return records is not important and will optimise for speed. (Checkout "EXPLAIN SELECT")

    CodeAddicts or Spudley's answer will give the result you want. An alternative is assigning a priority to the id's in "mytable" (or another table) and using this to order the records as desired.

提交回复
热议问题