如何从与比赛表相关的游戏表中获得比赛的获胜者?

时间:2011-08-05 20:54:44

标签: mysql relational-database tournament

在存储锦标赛的数据库中,我有这种关系结构来存储比赛及其游戏:

EER Diagram

当创建匹配时,插入匹配行和多个游戏行,对应于匹配中的游戏数量。还插入Match_left和match_right玩家行,然后将匹配中的两个玩家与匹配行相关联。当玩家被记录为赢得游戏时,与相应游戏相关的行被插入到game_winners表中。有没有办法编写一个查询来派出谁赢得了赢得比赛的比赛?也许逻辑上这应该是一个视图,以便我可以随时轻松地将匹配表行连接到它?

Here is some sample data

我希望弗雷德能够作为match_ID 1的赢家回归,因为他赢了2/3场比赛。我希望match_ID 2的获胜者为空,因为两位玩家都没有赢得必要的游戏数量(2/3)。

2 个答案:

答案 0 :(得分:0)

我在这里假设一场比赛的胜利者是赢得最多比赛的球员。

在比赛中对球员进行排名非常简单。

SELECT player_id, COUNT(*) AS game_count
  FROM game_winners
  WHERE match_id = ?
  GROUP BY player_id
  ORDER BY COUNT(*) DESC

一次找到多场比赛的获胜者是一个小问题。

SELECT match_id, player_id, COUNT(*) AS game_count
  FROM game_winners
  GROUP BY match_id, player_id

让我们调用上面的player_wins

SELECT match_id, MAX(game_count) AS match_winner
  FROM player_wins
  GROUP BY match_id

这为您提供每场比赛的胜利分数。

SELECT match_id, player_id
  FROM player_wins
  INNER JOIN (
    SEELCT match_id, MAX(game_count) AS match_winner
    FROM player_wins
    GROUP BY match_id
  ) AS winning_score
  ON player_wins.match_id = winning_score.match_id
  AND player_wins.game_count = winning_score.match_winner

这为每场比赛提供了获胜的球员。

答案 1 :(得分:0)

让我们看看我是否正确理解了您的样本数据。

SELECT match_id, round_id, COUNT(*) AS game_count
  FROM games
  GROUP BY match_id, round_id

这可以为您提供每场比赛的游戏数量。这场比赛是最好的比赛,所以你必须赢得超过一半的比赛才能赢得比赛。

SELECT match_id, round_id, player_id, COUNT(*) AS win_count
  FROM game_winners
  GROUP BY match_id, round_id

这将为您提供每场比赛中每位球员赢得的比赛数。

SELECT match_id, round_id, player_id
  FROM game_winners
  GROUP BY match_id, round_id
  HAVING COUNT(*) * 2 > (
    SELECT COUNT(*)
      FROM games
      WHERE games.match_id = game_winners.match_id
      AND games.round_id = game_winners.round_id
  )

因此,一个选项是添加一个检查,表明玩家通过子查询赢得了比赛中一半以上的比赛。

SELECT games_won.match_id, games_won.round_id, games_won.player_id
  FROM (
    SELECT match_id, round_id, player_id, COUNT(*) AS win_count
      FROM game_winners
      GROUP BY match_id, round_id
    ) AS games_won
  INNER JOIN (
    SELECT match_id, round_id, COUNT(*) AS game_count
      FROM games
      GROUP BY match_id, round_id
    ) AS all_games
  ON games_won.match_id = game_count.match_id
  AND games_won.round_id = game_count.round_id
  WHERE games_won.win_count * 2 > all_games.game_count

或者,如果您愿意,可以使用联接来完成。