“WHERE字段IN”SQL查询的顺序?

时间:2010-10-24 23:50:49

标签: sql mysql sql-order-by

我使用以下SQL从MySQL数据库中选择记录:

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

结果顺序等于“ORDER BY id ASC”,因此在示例记录中返回1,3,22。如何以IN子句中输入的确切方式对它们进行排序?订购为3,22,1?谢谢。

5 个答案:

答案 0 :(得分:7)

众多选择 -

CASE:

首选,是ANSI-92,可以移植到其他数据库。

  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');

字段:

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

参考:

答案 1 :(得分:6)

尝试使用ORDER BY FIELD,例如:

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

source here

答案 2 :(得分:1)

它可能不是很整洁,但您可能想要执行以下操作:

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)

<强>更新

@Dave@OMG Ponies建议的... ORDER BY FIELD (id, 3, 22, 1)会返回相同的结果,实际上更加整洁。

答案 3 :(得分:0)

你不能,它必须是ASC或DESC。

答案 4 :(得分:0)

按字段排序(id,'3','22','1')???