我理解正常的 ASC
和 DESC
ORDER BY
子句。
但是,我有一个情况,其中表包含一个列 unitType
,其中 unitType
可以是 0、1 或 2。我需要对结果集进行排序,以便行返回的顺序取决于 unitType
列的值。
这是我得到的最接近的:
SELECT * FROM `units` WHERE `unitType`=0
union
select * from units where unitType=2
union
select * from units where unitType=1
这列出了我的带有 unitType=0
的行,然后是值为 2 的行,最后是 1 的行。有没有更好的方法来做到这一点?我需要更改此查询以按任何特定顺序获取行,例如2、0、1 等
最佳答案
SELECT *
FROM units
WHERE unitType IN (0,1,2)
ORDER BY CASE WHEN unitType = 0 THEN 1
WHEN unitType = 2 THEN 2
WHEN unitType = 1 THEN 3
END
关于mysql - 以不自然的顺序排列结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8898545/