从一个表字段添加数字到另一个表字段?

时间:2011-05-22 13:01:58

标签: php mysql html phpmyadmin

我想知道如何将一个表字段中的数字添加到另一个表字段中,例如,我有:

Table name = Game: 

opponent1(name of row) vs. opponent 2    -  score1 = 25 - score2 =  20

我希望表“团队”能够自动更新以下内容:

Table name = Teams: 

Opponent1: 

  Points in favor = 25
  Points against  = 20

Opponent 2: 

   Points in favor = 20
  Points against  = 25

那是什么代码?可能是(有一些伪代码):

  • 如果得分1大于得分2
    • 将score1添加到表“team”中的“pointsfavor”字段到opponent1
    • 并将$ score2添加到表“团队”中的“pointsagainst”到opponent1

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

假设您的表具有以下结构:

TABLE team
  id integer autoincrement primary key,
  name varchar,
  pointsfavor integer,
  pointscontra integer

TABLE game
  id integer autoincrement primary key,
  team1_id integer,
  team2_id integer,
  score1 integer, /*score for team1*/
  score2 integer /*score for team2*/

您的更新语句可能如下所示:

UPDATE team 
INNER JOIN game g1 ON (team.id = g1.team1_id)
INNER JOIN game g2 ON (team.id = g2.team2_id)
SET pointsfavor = pointsfavor 
      + IF(g1.score1 > g1.score2, g1.score1 - g1.score2, 0) 
      + IF(g2.score2 > g2.score1, g2.score2 - g2.score1, 0)
  , pointscontra = pointscontra 
      + IF(g1.score1 < g1.score2, g1.score2 - g1.score1, 0) 
      + IF(g2.score2 < g2.score1, g2.score1 - g2.score2, 0)
WHERE game.id = 10;