avoid Sorting by the MYSQL IN Keyword

后端 未结 4 505
伪装坚强ぢ
伪装坚强ぢ 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 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;
    

提交回复
热议问题