MySQL分级/梯形图系统
我有两张桌子: *tbl_比赛*MySQL分级/梯形图系统,mysql,Mysql,我有两张桌子: *tbl_比赛* id contestant_1 contestant_2 winner *tbl_选手* id name 目标是获得每位参赛者的获胜百分比。也就是说,计算每个参赛者赢了多少场比赛,然后除以每个参赛者参加的比赛总数。这目前正在运行,但似乎很麻烦: SELECT all_matches.contestant_id, num_matches, num_wins, (num_wins / num_matches * 100.0) AS win_percen
id
contestant_1
contestant_2
winner
*tbl_选手*
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
我觉得这类事情以前一定做过,我正在寻找一些帮助来优化这一点,或者寻找一个链接到一个更好的人已经做过的事情我会尝试这种方法:
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
考虑提供适当的DDL(和/或SqLFIDLE)以及期望的结果集-1:没有解释计划,没有创建表语句,没有索引细节,(在较小程度上,没有对非规范化模式设计的解释,没有理由选择每一个参赛者)很好。非常感谢。