MySQL Select WHERE IN given order

前端 未结 7 1833
时光取名叫无心
时光取名叫无心 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.

    0 讨论(0)
  • 2020-12-07 21:07

    this is the first thing that pops to mind. note sql is untested, you might need to check correct syntax

    its a bit cumbersome, but might do the trick

    select * from table where id = 118
    union 
    select * from table where id = 17
    union 
    .... and so on
    
    0 讨论(0)
  • 2020-12-07 21:11

    I think if you did a UNION query with each select, it might return it in the order.

    SELECT * FROM table WHERE id=118
    UNION
    SELECT * FROM table WHERE id=17
    ...
    

    Ugly, but I think it will work.

    0 讨论(0)
  • 2020-12-07 21:14

    You should use "ORDER BY FIELD". So, for instance:

    SELECT * FROM table WHERE id IN (118,17,113,23,72) 
    ORDER BY FIELD(id,118,17,113,23,72)
    
    0 讨论(0)
  • 2020-12-07 21:15

    You can create a number to sort on based on the id values:

    select *
    from table
    where id in (118,17,113,23,72)
    order by
      case id
        when 118 then 1
        when 17 then 2
        when 133 then 3
        when 23 then 4
        when 72 then 5
      end
    
    0 讨论(0)
  • 2020-12-07 21:21

    Try using FIND_IN_SET:

    SELECT * FROM table WHERE id IN (118,17,113,23,72) 
        ORDER BY FIND_IN_SET(id, '118,17,113,23,72');
    
    0 讨论(0)
提交回复
热议问题