使用if或其他内容更改订单输出

时间:2013-03-20 19:54:55

标签: mysql

SELECT *,`kills`-`deaths` as x FROM `users` ORDER BY `x` DESC LIMIT 0,50;

表:

user|kills|deaths
a   | 10  | 9
b   | 11  | 9
c   | 0   | 0
d   | 0   | 0
e   | 0   | 0
f   | 1   | 5

输出将是:

b | 2
a | 1
c | 0
d | 0
e | 0
f | -4

我需要这样的输出:

b | 2
a | 1
f | -4
c | 0
d | 0
e | 0

因为用户处于活动状态并且他已经死亡,其他用户处于非活动状态,因此他们会进入最低点。

怎么做?

3 个答案:

答案 0 :(得分:2)

SELECT *, kills-deaths as x 
FROM users 
ORDER BY x = 0, x DESC LIMIT 0,50;

SqlFiddle

答案 1 :(得分:0)

只需将您的活动度量添加到order by子句。

SELECT *, (kills-deaths) as x 
FROM users 
ORDER BY ((kills+deaths) <> 0), x DESC 
LIMIT 50 OFFSET 0

答案 2 :(得分:0)

我通常的快速解决方案是使用

SELECT user,`kills`-`deaths` as x 
FROM `users` 
group by user 
ORDER BY `x` DESC 
LIMIT 0,50;

在这里你也可以

SELECT user,`kills`-`deaths` as x 
FROM `users` 
ORDER BY `kills`-`deaths` DESC 
LIMIT 0,50;

我使用group by使任何计算只在一个地方进行并且是一致的。