-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
我覺得像這樣的事情必須已經做過了,我正在尋找一些幫助優化這還是一個更好的人已經做
考慮提供適當的DDL(和/或一個sqlfiddle)與期望的結果集 – Strawberry
-1:沒有解釋計劃,沒有創建表語句,沒有索引細節,(對於非規範化模式設計沒有解釋,沒有選擇每個參賽者的理由) – symcbean