MySQL Select WHERE IN given order

前端 未结 7 1832
时光取名叫无心
时光取名叫无心 2020-12-07 20:26

I have something like

SELECT * FROM table WHERE id IN (118,17,113,23,72);

If I just do this it returns the rows in ID ascending order. Is t

7条回答
  •  囚心锁ツ
    2020-12-07 21:07

    You can create a temp table with two columns (ID, order_num):

    ID   order_num
    118  1
    17   2
    113  3
    23   4
    72   5
    

    Then join:

    SELECT * from table
    INNER JOIN #temp_table 
    ON table.id = #temp_table.id
    

    Notice that you can drop the IN clause.

    Sometimes I actually create a permanent table, because then when the client inevitably changes their mind about the ordering, I don't have to touch the code, just the table.

    Edit

    The answer using ORDER BY FIELD() (which I didn't know about) is probably what you want.

提交回复
热议问题