复杂的mysql排名!

时间:2010-04-21 01:31:56

标签: mysql hierarchy ranking performance

我有一个包含这些列的表:win,los,id ......

我想按此指数订购表格:win /(win + los)* 30 + win / SUM(win)* 70  然后找到两个id的等级。   我对mysql不太了解,所以我写的完全错了。 (它使用Perl + DBI + DBD :: mysql):

$stmt=$con->prepare("SET @rk := 0");
$stmt=$con->prepare("SELECT rank, id FROM (
                           SELECT @rk := @rk + 1 AS rank,                
                                (win/(win+los)*30+win/SUM(win)*70) AS index,
                                win, los, id 
                          FROM tb_name ORDER BY index DESC) as result 
                   WHERE id=? AND id=?"); 
$stmt -> bind_param ("ii", $id1, $id2);
$stmt -> execute();
$stmt -> bind_result($rk, $idRk); 

而且这个查询假设每个用户可能每5-10秒运行一次,所以我试图找到非常非常快的东西。     如果有必要,我可以添加,更改,删除任何列,以便尽可能快。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT rank, id FROM (
    SELECT @rk := @rk + 1 AS rank,                
    (win/(win+los)*30+win/win_sum*70) AS index, -- SUM(win) -> win_sum
    win, los, id 
    FROM tb_name,
    (SELECT SUM(win) as win_sum FROM tb_name) as ws -- separated SUM(win)
    ORDER BY index DESC) as result
WHERE id IN (?, ?);    -- id=? AND id=? will never happen, should be OR

('win','los')的综合索引可能很有用。

答案 1 :(得分:0)

您在SELECT语句中使用的任何扩展也可以进入ORDER BY表达式。

您也可以为表达式指定列别名并按别名排序。

如果你对mysql不满意,那么我建议你自己开发查询,而不是试图同时将它嵌入预备语句中。