MySQL JOIN,我无法解决这个问题

时间:2015-02-16 15:49:04

标签: mysql join

我有三个表(两个很重要,一个只是为了澄清),如下所示:

_team_ID         name
       1    Blue Team
       2   Green Team
       3   Black Team

游戏

_game_ID   _team_left_ID   _team_right_ID
       1               1                2
       2               2                1
       3               1                2

game_points

_game_points_ID   _game_ID   _team_ID
              1          1          1
              2          1          1
              3          1          2
              4          1          1
              5          2          2

_team_ID位于_team_left_ID或_team_right_ID中,具体取决于他们从哪一方开始。

game_points中的

_team_ID是得分的球队。所以需要在某个地方有一个COUNT()。

我想要达到的目标是获得多少分_team_ID 1和2并且在每场比赛中得分,并且得分最高。

基本上这个:

_game_ID   _team_left_ID   _team_right_ID   left_points   right_points   winner
       1               1                2             3              1        1
       2               2                1             1              0        2
       3               1                2             0              0     NULL

请帮忙!

1 个答案:

答案 0 :(得分:0)

我当然没有对此进行测试,但我相信这应该会让你朝着正确的方向前进。我不确定选择的最后一行是否有效,但更糟糕的是你可以比较左点和右点以确定胜利者。

SELECT
game._game_ID,
left_team._team_ID,
right_team._team_ID,
SUM(game_points._team_ID = left_team._team_ID) as left_pts,
SUM(game_points._team_ID = right_team._team_ID) as right_pts,
IF(SUM(game_points._team_ID = left_team._team_ID) = SUM(game_points._team_ID = right_team._team_ID),NULL,IF(SUM(game_points._team_ID = left_team._team_ID) > SUM(game_points._team_ID = right_team._team_ID), left_team._team_ID, right_team._team_ID)) as winner
FROM game
INNER JOIN team as left_team ON left_team._team_ID = game._team_left_ID
INNER JOIN team as right_team ON right_team._team_ID = game._team_right_ID
LEFT JOIN game_points ON game_points._game_ID = game._game_ID
GROUP BY game._game_ID

添加最终用例只是为了清除答案。

SELECT
game._game_ID,
left_team._team_ID,
right_team._team_ID,
SUM(game_points._team_ID = left_team._team_ID) as left_pts,
SUM(game_points._team_ID = right_team._team_ID) as right_pts,
CASE WHEN SUM(game_points._team_ID = left_team._team_ID) > SUM(game_points._team_ID = right_team._team_ID) THEN left_team._team_ID WHEN SUM(game_points._team_ID = left_team._team_ID) < SUM(game_points._team_ID = right_team._team_ID) THEN right_team._team_ID ELSE NULL END AS winner
FROM game
INNER JOIN team as left_team ON left_team._team_ID = game._team_left_ID
INNER JOIN team as right_team ON right_team._team_ID = game._team_right_ID
LEFT JOIN game_points ON game_points._game_ID = game._game_ID
GROUP BY game._game_ID