2014-02-20 35 views
-1

我有兩個表: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 

我覺得像這樣的事情必須已經做過了,我正在尋找一些幫助優化這還是一個更好的人已經做

+0

考慮提供適當的DDL(和/或一個sqlfiddle)與期望的結果集 – Strawberry

+0

-1:沒有解釋計劃,沒有創建表語句,沒有索引細節,(對於非規範化模式設計沒有解釋,沒有選擇每個參賽者的理由) – symcbean

回答

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 
+0

很好,這是完美的。謝謝! –