avoid Sorting by the MYSQL IN Keyword

牧云@^-^@ 提交于 2019-11-28 04:47:04

问题


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:

SELECT id ,title, date FROM Table WHERE id in (7,1,5,9,3)

in return the result provided is in the order 1,3,5,7,9.

How can i avoid this auto sorting


回答1:


If you want to order your result by id in the order specified in the in clause you can make use of FIND_IN_SET as:

SELECT id ,title, date 
FROM Table 
WHERE id in (7,1,5,9,3)
ORDER BY FIND_IN_SET(id,'7,1,5,9,3')



回答2:


There is no auto-sorting or default sorting going on. The sorting you're seeing is most likely the natural sorting of rows within the table, ie. the order they were inserted. If you want the results sorted in some other way, specify it using an ORDER BY clause. There is no way in SQL to specify that a sort order should follow the ordering of items in an IN clause.




回答3:


The WHERE clause in SQL does not affect the sort order; the ORDER BY clause does that.

If you don't specify a sort order using ORDER BY, SQL will pick its own order, which will typically be the order of the primary key, but could be anything.

If you want the records in a particular order, you need to specify an ORDER BY clause that tells SQL the order you want.

If the order you want is based solely on that odd sequence of IDs, then you'd need to specify that in the ORDER BY clause. It will be tricky to specify exactly that. It is possible, but will need some awkward SQL code, and will slow down the query significantly (due to it no longer using a key to find the records).

If your desired ID sequence is because of some other factor that is more predictable (say for example, you actually want the records in alphabetical name order), you can just do ORDER BY name (or whatever the field is).

If you really want to sort by the ID in an arbitrary sequence, you may need to generate a temporary field which you can use to sort by:

SELECT *,
CASE id
  WHEN 7 THEN 1
  WHEN 1 THEN 2
  WHEN 5 THEN 3
  WHEN 3 THEN 4
  WHEN 9 THEN 5
END AS mysortorder
FROM mytable
WHERE id in (7,1,5,9,3)
ORDER BY mysortorder;



回答4:


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.



来源:https://stackoverflow.com/questions/4195642/avoid-sorting-by-the-mysql-in-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!