SQL 复杂 SELECT 查询
SQL complicated SELECT query
我想要一个 select 查询,我可以在其中获取特定用户使用他和对手球队的积分进行的所有比赛。
我的数据库的实体关系模型
这是我当前的查询:
Select playsIn.userId,game.id AS "gameId", plays.won, team.points from game JOIN plays ON plays.gameId = game.id
JOIN team ON team.id = plays.teamId JOIN playsIn ON team.id = playsIn.teamId WHERE playsIn.userId = 2
当前查询给了我这样的结果:
userId
gameId
won
points
1
1
true
19
问题:
从这个查询中我只得到我队的积分,但我也想得到其他队的积分。不知道对方的积分怎么算。
结果应该是这样的:
userId
gameId
won
pointsMyTeam
pointsOtherTeam
1
1
true
19
14
注意:一场比赛总是只有 2 支球队。
感谢您的帮助!
听起来您需要加入该游戏的另一 plays
行,匹配游戏 ID 但不匹配团队 ID 的行:
JOIN plays otherplays ON otherplays.gameId = game.id AND otherplays.teamId <> team.id
然后您可以将其加入另一 team
行:
JOIN team otherteam ON otherteam.id = otherplays.teamId
然后可以selectotherteam.points
。顺便说一下,请考虑将 points
作为 plays
table 的一列,而不是 team
table。通过使 points
成为 team
的一列,您可以限制每支球队只有一个分值,因此只能玩一场比赛。
我想要一个 select 查询,我可以在其中获取特定用户使用他和对手球队的积分进行的所有比赛。
我的数据库的实体关系模型
这是我当前的查询:
Select playsIn.userId,game.id AS "gameId", plays.won, team.points from game JOIN plays ON plays.gameId = game.id
JOIN team ON team.id = plays.teamId JOIN playsIn ON team.id = playsIn.teamId WHERE playsIn.userId = 2
当前查询给了我这样的结果:
userId | gameId | won | points |
---|---|---|---|
1 | 1 | true | 19 |
问题: 从这个查询中我只得到我队的积分,但我也想得到其他队的积分。不知道对方的积分怎么算。
结果应该是这样的:
userId | gameId | won | pointsMyTeam | pointsOtherTeam |
---|---|---|---|---|
1 | 1 | true | 19 | 14 |
注意:一场比赛总是只有 2 支球队。
感谢您的帮助!
听起来您需要加入该游戏的另一 plays
行,匹配游戏 ID 但不匹配团队 ID 的行:
JOIN plays otherplays ON otherplays.gameId = game.id AND otherplays.teamId <> team.id
然后您可以将其加入另一 team
行:
JOIN team otherteam ON otherteam.id = otherplays.teamId
然后可以selectotherteam.points
。顺便说一下,请考虑将 points
作为 plays
table 的一列,而不是 team
table。通过使 points
成为 team
的一列,您可以限制每支球队只有一个分值,因此只能玩一场比赛。