SQL query order "WHERE field IN"?

I use the following SQL to select records from a MySQL database:

SELECT * FROM cms_product WHERE id IN (3,22,1);

The order of the results is "ORDER BY id ASC", since the records 1,3,22 are returned in the example. How can I get them in an ordered, exact way, as indicated in the IN section? So ordered as 3.22.1? Thank.

+5
source share
5 answers

Numerous options -

CASE:

Preferred as ANSI-92, it is ported to other databases.

  SELECT * 
    FROM cms_product 
   WHERE id IN (3,22,1)
ORDER BY CASE id
           WHEN 3 THEN 1
           WHEN 22 THEN 2
           WHEN 1 THEN 3
         END

FIND_IN_SET:

  SELECT * 
    FROM cms_product 
   WHERE id IN (3,22,1)
ORDER BY FIND_IN_SET(id, '3,22,1');

Region:

  SELECT * 
    FROM cms_product 
   WHERE id IN (3,22,1)
ORDER BY FIELD(id, 3, 22, 1);

Link:

+7
source

Try using ORDER BY FIELDfor example:

SELECT * FROM cms_product WHERE id IN (3,22,1) ORDER BY FIELD (id, 3, 22, 1);

source here

+6
source

, :

SELECT    * 
FROM      cms_product 
WHERE     id IN (3, 22, 1)
ORDER BY  id = 3 DESC, id = 22 DESC, id = 1 DESC;

:

CREATE TABLE cms_product (id int, value int);

INSERT INTO cms_product VALUES (1, 100);
INSERT INTO cms_product VALUES (3, 200);
INSERT INTO cms_product VALUES (22, 300);

:

+------+-------+
| id   | value |
+------+-------+
|    3 |   200 |
|   22 |   300 |
|    1 |   100 |
+------+-------+
3 rows in set (0.02 sec)

UPDATE:

... ORDER BY FIELD (id, 3, 22, 1)as suggested by @Dave and @OMG Ponies returns the same results and is actually a lot neater.

+1
source

You cannot, it must be ASC or DESC.

0
source

ORDER BY FIELD ( id, '3', '22', '1')

0
source

All Articles