1

我正在为测验碗创建一个 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);

我的问题是如何game_results使用 MySQL 从表中计算球队的胜利次数(即球队在特定比赛中得分最高的球队的次数)。

4

2 回答 2

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
于 2012-06-06T04:57:02.193 回答
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
于 2012-06-06T05:27:53.187 回答