我正在尝试获取我的数据库中每个团队的赢/输记录。我觉得我很接近,但我似乎无法迈出最后一步。
表格如下所示:
GameID | TeamAID | TeamBID | Winner
-----------------------------------
1 1 2 1
2 3 5 3
... ... ... ...
使用我的尝试链接到MySQL Fiddle:http://sqlfiddle.com/#!2/26b00/7
我解决这个问题的方法是首先找到每支球队的比赛次数,然后找出每支球队的胜利次数,最后从比赛中减去胜利数来获得赔率。
我想出的查询游戏数量的查询如下:
SELECT Game.TeamAID, TA.Count + TB.Count AS Sum
FROM Game
LEFT JOIN (SELECT TeamAID, COUNT(GameID) AS Count
FROM Game
GROUP BY TeamAID) AS TA ON TA.TeamAID = Game.TeamAID
LEFT JOIN (SELECT TeamBID, COUNT(GameID) AS Count
FROM Game
GROUP BY TeamBID) AS TB ON TB.TeamBID = Game.TeamAID
GROUP BY TeamAID
这成功地为我提供了每个参加过比赛的球队以及球队比赛的数量。
接下来是问题出现的时候。
这是我给出的每个团队获胜次数的查询:
SELECT Game.TeamAID, TA.Cnt + TB.Cnt AS Sum
FROM Game
LEFT JOIN (SELECT TeamAID, COUNT(GameID) AS Cnt
FROM Game
WHERE TeamAID = Winner
GROUP BY TeamAID
ORDER BY TeamAID) AS TA ON TA.TeamAID = Game.TeamAID
LEFT JOIN (SELECT TeamBID, COUNT(GameID) AS Cnt
FROM Game
WHERE TeamBID = Winner
GROUP BY TeamBID
ORDER BY TeamBID) AS TB ON TB.TeamBID = Game.TeamAID
GROUP BY TeamAID;
这给我的问题是,在某些情况下,当某个特定团队在作为TeamA或TeamB玩游戏时没有赢得任何比赛时,它会在联接后返回null。
有没有办法获得每个团队赢得的游戏数量,这样我就不会得到结果为null的问题?或者更好的是,我忽略了一个更简单的问题解决方案吗?
我最终希望结果看起来像:
TeamID | Wins | Losses
----------------------
6 18 1
... ... ...
感谢Adam V带领我找到了帮助我解决问题的IFNULL功能。
解决方案如下:
SELECT Game.TeamAID, GP.Sum AS GamesWon, ((TA.CA + TB.CB) - GP.Sum) AS GameLost
FROM Game
LEFT JOIN (SELECT TeamAID, COUNT(GameID) AS CA
FROM Game
GROUP BY TeamAID
) AS TA ON TA.TeamAID = Game.TeamAID
LEFT JOIN (SELECT TeamBID, COUNT(GameID) AS CB
FROM Game
GROUP BY TeamBID
) AS TB ON TB.TeamBID = Game.TeamAID
LEFT JOIN (SELECT Game.TeamAID, IFNULL(TA.Cnt,0) + IFNULL(TB.Cnt,0) AS Sum
FROM Game
LEFT JOIN (SELECT TeamAID, COUNT(GameID) AS Cnt
FROM Game
WHERE TeamAID = Winner
GROUP BY TeamAID
ORDER BY TeamAID
) AS TA ON TA.TeamAID = Game.TeamAID
LEFT JOIN (SELECT TeamBID, COUNT(GameID) AS Cnt
FROM Game
WHERE TeamBID = Winner
GROUP BY TeamBID
ORDER BY TeamBID
) AS TB ON TB.TeamBID = Game.TeamAID
GROUP BY TeamAID
) AS GP ON GP.TeamAID = Game.TeamAID
GROUP BY TeamAID