简体   繁体   中英

How to select mysql rows in the order of IN clause

For example I have in the table EMPLOYEE:

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

if you do: (select * from EMPLOYEE) you will get:

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

if you do: (select * from EMPLOYEE where code in (1,3,2,4) you will get:

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

How to get it in the order of CSV values in the IN clause, as is?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM