MySQL:仅排序大于特定值的值

时间:2014-05-11 16:50:42

标签: mysql sql

我有下表:

CREATE TABLE `data`
(`id` int, `x` int, `y` int);

INSERT INTO `data`
(`id`, `x`, `y`)
VALUES
(1, 5, 7),
(2, 9, 3),
(3, 4, 6),
(4, 0, 0),
(5, 0, 0),
(6, -1, 2);

我需要从表中选择所有数据,然后按对(x,y)中的最大值对它们进行排序。但只有x和y都大于0的值。其中一对(x,y)小于0的行应该放在有序值的下面,其余的行放在所选列表的末尾。

我有以下SQL查询:

SELECT `x`, `y`, GREATEST (`x`, `y`) as `result` FROM `data`
ORDER BY `result`=0, `result`=-1, `result` ASC

给了我以下结果:

X   Y   RESULT
-1  2   2
4   6   6
5   7   7
9   3   9
0   0   0
0   0   0

但我希望的结果是:

X   Y   RESULT
4   6   6
5   7   7
9   3   9
-1  2   2
0   0   0
0   0   0

SQLfiddle:http://www.sqlfiddle.com/#!2/995d2/6

1 个答案:

答案 0 :(得分:4)

这是使用case-when

执行此操作的方法
SELECT 
`x`, 
`y`, 
GREATEST (`x`, `y`) as `result` 
FROM `data` 
ORDER BY 
case 
  when x > 0 and y > 0 then 0 
  when x < 0  OR y < 0 then 1
  when result = 0 then 2
end,
result
ASC

<强> DEMO

相关问题