我正在为测验碗创建一个MySQL数据库。设计是有一个包含所有游戏结果的交叉表,交叉表的格式为:
CREATE TABLE game_results(
id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
game_id MEDIUMINT NOT NULL,
team_id SMALLINT NOT NULL,
score MEDIUMINT);
我的问题是如何使用MySQL从表game_results
计算一个团队获胜的数量(即,团队是特定游戏中得分最高的团队的次数)。
答案 0 :(得分:2)
SELECT COUNT(1) AS wins FROM game_results AS gr1
LEFT JOIN game_results AS gr2 ON gr1.game_id=gr2.game_id AND gr2.team_id != 1234
WHERE gr1.team_id = 1234 AND gr1.score > gr2.score
答案 1 :(得分:1)
SELECT old.team_id,
COUNT(old.team_id) AS Wins,
old.game_id
FROM game_results AS old,
(SELECT MAX(score) AS score,
game_id
FROM game_results
GROUP BY game_id) AS nt
WHERE old.score = nt.score
AND old.game_id = nt.game_id
GROUP BY old.team_id
编辑:忽略抽奖游戏
SELECT old.team_id,
COUNT(old.team_id) AS Wins,
old.game_id
FROM game_results AS old,
(SELECT MAX(score) AS score,
game_id
FROM game_results
GROUP BY game_id) AS nt
WHERE old.score = nt.score
AND old.game_id = nt.game_id
AND old.game_id NOT IN
(SELECT DISTINCT a.game_id
FROM game_results AS a,
game_results AS b
WHERE a.game_id = b.game_id
AND a.score = b.score
AND a.id != b.id)
GROUP BY old.team_id