0

我正在编写一个脚本,该脚本根据从 MySQL 表中获得的值计算杀伤率 (KDR)。我正在修复别人的代码。我已经设法让它的大部分再次工作。但是,我被困在这里。KDR 的计算方法是将所有击杀数相加,然后除以玩家的死亡数。但是,如果玩家从未死过,那么 KDR 的值为 0。我需要一种读取 0 的方法,在评估 KDR 时将其作为 1。我确实谷歌了这个,并尝试编写一个我可以使用的 UDF,但是它没有帮助。

下面是有问题的 SQL 查询

function get_leaders($civ, $neu, $riv){
    $sSQL = "SELECT *, ((civilian_kills * _civ + neutral_kills * _neu + rival_kills * _riv) / deaths ) as KDR
              from sc_players
              order by KDR DESC
              LIMIT 100;";
4

2 回答 2

4

http://dev.mysql.com/doc/refman/5.5/en/control-flow-functions.html#function_if

SELECT *,
IF(deaths,civilian_kills * $civ + neutral_kills * $neu + rival_kills * $riv) / deaths,1) as KDR
from sc_players
order by KDR DESC
LIMIT 100
于 2012-06-24T19:43:09.513 回答
1

I think you mean the divisor should be treated as 1 when it is 0. In that case, you would do

SELECT *, ((civilian_kills * $civ + neutral_kills * $neu + rival_kills * $riv) / 
    (IF deaths = 0 THEN 1 ELSE deaths)
) as KDR from sc_players order by KDR DESC LIMIT 100;

Assuming deaths is nonnegative, you could also do:

SELECT *, ((civilian_kills * $civ + neutral_kills * $neu + rival_kills * $riv) / 
    GREATEST(deaths, 1)
) as KDR from sc_players order by KDR DESC LIMIT 100;
于 2012-06-24T19:55:49.507 回答