根据条件更新SQL表。

时间:2014-01-13 06:10:34

标签: mysql

这是我的表结构

Teams (Table Name) 
TeamID      TeamName       TotalScore 
01          Cowboys        6 
02          Bulldogs 
03          Broncos 
04          Raiders

Games (Table Name) 
GameID    team1     team2     team1score team2score Winner GameStart            Status 
01        01        03                                     02/04/2014 07:00:00    0 
02        02        04        6          10         04     03/04/2014 05:30:00    2

Users (Table Name) 
userID      Username      Password    Main Team   Points 
01          Brodey        abc         02          3

Tips (Table Name) 
TipID     userID      GameID       TippedTeam 
01        01          01           02 
02        01          02           03

如果game status = 2检查Tips。如果TippedTeamGames的获胜者匹配,则更新Users points +3。如果获胜者不匹配,请不要更新。

我尝试了这个,但它不起作用:

update users as u,  tips as t 
set u.points = u.points +3
where u.userid = t.userid 
and tips.tippedteam = (select winner from games where status=2)

请帮忙

1 个答案:

答案 0 :(得分:1)

加入所有3个表,试试这个:

update users as u, tips, games as g
set u.points = u.points + 3 
where u.userid = tips.userid 
and tips.gameid = g.gameid
and tips.tippedteam = g.winner 
and g.status=2

对于您的第二个请求(在评论中提出),请尝试以下方法:

update teams
join games
on teams.teamID = games.team1
set totalscore = CASE WHEN teams.teamID = games.team1 THEN IFNULL(TotalScore,0)+games.team1score ELSE TotalScore END
where games.status = 2;

update teams
join games
on teams.teamID = games.team2
set totalscore = CASE WHEN teams.teamID = games.team2 THEN IFNULL(TotalScore,0)+games.team2score ELSE TotalScore END
where games.status = 2

更新查询(上面)合并为一个:

update teams
join games
on (teams.teamID = games.team1 or teams.teamID = games.team2)
set totalscore = 
      CASE 
      WHEN teams.teamID = games.team1 THEN IFNULL(TotalScore,0)+games.team1score 
      WHEN teams.teamID = games.team2 THEN IFNULL(TotalScore,0)+games.team2score 
      ELSE TotalScore 
      END
where games.status = 2