Sort by order of values in a select statement “in” clause in mysql

后端 未结 4 880
挽巷
挽巷 2020-11-28 07:24

I\'m selecting a set of account records from a large table (millions of rows) with integer id values. As basic of a query as one gets, in a sense. What I\'m doing us build

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 08:11

    A bit of a trick....

    SELECT * FROM your_table
    WHERE id IN (5,2,6,8,12,1)
    ORDER BY FIND_IN_SET(id,'5,2,6,8,12,1') DESC;
    

    note that the list of ID's in the find_in_set is a string, so its quoted. Also note that without DESC, they results are returned in REVERSE order to what the list specified.

提交回复
热议问题