0

我正在制作一个浏览器黑手党游戏,并对列出所有家庭/帮派的页面进行编码。

每个家庭都有一个积分等级,由其所有成员现金、子弹、经验等的总和组成。

这是我循环显示家庭列表的代码:

SELECT 
 (SELECT COUNT(*) FROM players WHERE status='alive' AND family=f.id) as member_count,
 (SELECT SUM(bullets) FROM players WHERE status='alive' AND family=f.id) as sum_bullets,
 (SELECT SUM(cash) FROM players WHERE status='alive' AND family=f.id) as sum_cash,
 (SELECT SUM(exp) FROM players WHERE status='alive' AND family=f.id) as sum_exp,
 (SELECT SUM(killscore) FROM players WHERE status='alive' AND family=f.id) as sum_ks,
 name, id FROM familys f

然后在使用 PHP 的循环中,我计算出总分:

$points = $rs[sum_bullets]/500;
$points = $points + $rs[sum_cash]/10000;
$points = $points + $rs[sum_exp]/1000;
$points = $points + $rs[sum_ks];

现在谈这个问题。我想使用ORDER BY points DESC. 我怎样才能调整我的查询来做到这一点?

4

2 回答 2

0

您使用 php 计算的点在您的 mysql 代码中尚不存在,因此我建议通过 php 添加排序。类似于将所有点添加到数组中并使用默认的php 数组排序方法,或者如果您使用的是多级数组,请尝试Alecander Minkovskys 多排序库

于 2012-07-30T11:06:45.520 回答
0

尝试将逻辑从应用程序转移到 MySQL,以通过单个查询使其更快:

SELECT
    (SELECT COUNT(*) FROM players WHERE status='alive' AND family=f.id) as member_count,
    (SELECT SUM(bullets) FROM players WHERE status='alive' AND family=f.id) as sum_bullets,
    (SELECT SUM(cash) FROM players WHERE status='alive' AND family=f.id) as sum_cash,
    (SELECT SUM(exp) FROM players WHERE status='alive' AND family=f.id) as sum_exp,
    (SELECT SUM(killscore) FROM players WHERE status='alive' AND family=f.id) as sum_ks,
    name, id
FROM familys f
ORDER BY (sum_bullets/500 + sum_cash/10000 + sum_exp/1000 + sum_ks);

编辑:用于 total_points 的输出

SELECT a.*, (sum_bullets/500 + sum_cash/10000 + sum_exp/1000 + sum_ks) AS total_points
FROM
    (
     SELECT
        (SELECT COUNT(*) FROM players WHERE status='alive' AND family=f.id) as member_count,
        (SELECT SUM(bullets) FROM players WHERE status='alive' AND family=f.id) as sum_bullets,
        (SELECT SUM(cash) FROM players WHERE status='alive' AND family=f.id) as sum_cash,
        (SELECT SUM(exp) FROM players WHERE status='alive' AND family=f.id) as sum_exp,
        (SELECT SUM(killscore) FROM players WHERE status='alive' AND family=f.id) as sum_ks,
        name, id
     FROM familys f
    ) a
ORDER BY (sum_bullets/500 + sum_cash/10000 + sum_exp/1000 + sum_ks) ASC;
于 2012-07-30T11:07:48.613 回答