我使用以下SQL从MySQL数据库中选择记录:
SELECT * FROM cms_product WHERE id IN (3,22,1);
结果顺序等于“ORDER BY id ASC”,因此在示例记录中返回1,3,22。如何以IN子句中输入的确切方式对它们进行排序?订购为3,22,1?谢谢。
答案 0 :(得分:7)
众多选择 -
首选,是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
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);
答案 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')???