How to select mysql rows in the order of IN clause

后端 未结 2 1327
灰色年华
灰色年华 2020-12-30 08:05

For example I have in the table EMPLOYEE:

(code, name)
(1, \'Jimmy\')
(2, \'Albert\')
(3, \'Michelle\')
(4, \'Felix\' )

if you do: (select

相关标签:
2条回答
  • 2020-12-30 08:37

    The general solution to this problem, retaining the order based on your input (CSV) file, is to add an AUTO_INCREMENT column to your table and order based on that. You probably will never display it as part of your query, but you can order on it to get the original order in your input file, after the import.

    0 讨论(0)
  • 2020-12-30 08:55

    Use the FIND_IN_SET function:

    SELECT e.* 
      FROM EMPLOYEE e 
     WHERE e.code in (1,3,2,4) 
    ORDER BY FIND_IN_SET(e.code, '1,3,2,4')
    

    Or use a CASE statement:

    SELECT e.* 
      FROM EMPLOYEE e 
     WHERE e.code in (1,3,2,4) 
    ORDER BY CASE e.code
               WHEN 1 THEN 1 
               WHEN 3 THEN 2
               WHEN 2 THEN 3
               WHEN 4 THEN 4
             END
    
    0 讨论(0)
提交回复
热议问题