MySQL评级/阶梯系统

时间:2014-02-20 22:26:21

标签: mysql

我有两张桌子:

* tbl_MATCHES *

id
contestant_1
contestant_2
winner

* tbl_CONTESTANTS *

id
name

目标是获得每位参赛者的胜率。也就是说,计算每个参赛者赢得多少场比赛,并将其除以每个参赛者参加的比赛总数。这目前正在运作,但似乎很麻烦:

SELECT all_matches.contestant_id, num_matches, num_wins, 
    (num_wins / num_matches * 100.0) AS win_percent FROM ( 

        // get total number of wins for each contestant

        SELECT contestants.id AS contestant_id, 
        COUNT(matches.winner) AS num_wins 
        FROM contestants 
        LEFT JOIN matches 
        ON matches.winner = contestants.id 
        GROUP BY matches.winner 
    ) all_matches 

    // join total number of wins to total number of matches played

    JOIN ( 
        SELECT contestant_id, COUNT(contestant_id) AS num_matches FROM ( 

            // get list of all matches played by all contestants

            SELECT contestants.id AS contestant_id 
            FROM matches 
            JOIN contestants ON contestants.id = matches.contestant_1 
            UNION ALL 
            SELECT contestants.id AS contestant_id 
            FROM matches 
            JOIN contestants ON contestants.id = matches.contestant_2 
        ) all_m 
        GROUP BY contestant_id 
    ) all_matches 
    ON all_matches.contestant_id = all_matches.contestant_id 
    ORDER BY win_percent DESC

我觉得以前必须做过这样的事情,我正在寻找一些帮助来优化这个或者找到一个更好的人已经完成的链接

1 个答案:

答案 0 :(得分:1)

我会尝试这种方法:

SELECT 
    contestants.id AS contestant_id,
    COUNT(*) AS num_matches,
    SUM( CASE WHEN matches.winner = contestants.id THEN 1 ELSE 0 END ) 
        AS num_wins,
    SUM( CASE WHEN matches.winner = contestants.id THEN 1 ELSE 0 END ) 
        / COUNT(*) * 100 AS win_percent 
FROM matches 
JOIN contestants 
ON contestants.id IN( matches.contestant_1, matches.contestant_2 ) 
GROUP BY contestants.id