views:

68

answers:

2

I have a table with these columns: win, los, id ...

I want to order the table by this index: win / ( win + los ) * 30 + win / SUM(win) * 70 and then to find the rank for two id's. I'm not very good on mysql, so what I wrote is totally wrong. (It uses 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); 

And also this query it suppose to run maybe every 5-10 sec for every user, so I'm trying to find something very, very fast. If it's necessary I could add, change, delete any column, in order to be as fast as possible.

A: 

Whatever experession you use in the SELECT statement can also go into your ORDER BY expression.

You can also assign the expression a column alias and order by the alias, as you've done.

If you're not comfortable with mysql then I suggest you develop your query on its own rather than trying to embed it in a prepared statement at the same time.

le dorfier
i'm new in webdevelopment so in fact I'm more comfortable with prepared statements. I already tryied your first suggestion but neither in that way I couldn't make it work
@silversky: What he means is that you should play with it in MySQL's command prompt until you're comfortable that it does what you want. Then you should copy it into your code.
Ken Bloom
@silversky: and if you don't really like the mysql-command prompt (it works, but I still don't like it ... :-), then use one of the MySQL query tools: http://stackoverflow.com/questions/9185/what-is-the-best-mysql-client-application-for-windows will give you many tips!
lexu
A: 

Try this one:

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

A composite index on ('win', 'los') might be useful.

newtover