【问题标题】:Add numbers from one table field to another?将数字从一个表字段添加到另一个?
【发布时间】:2011-08-30 14:13:41
【问题描述】:

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

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

那会是什么代码?会不会(有一些伪代码):

  • 如果 score1 大于 score2
    • 将 score1 添加到表“team”中的“pointsfavor”字段到对手 1
    • 并将 $score2 添加到表“team”中的“pointsagainst”到对手1

有人可以帮帮我吗?

【问题讨论】:

    标签: php mysql html phpmyadmin


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 谢谢! .. 这是做什么的:WHERE game.id = 10;?
    • 它只更新第 10 场比赛的分数,如果你不添加 where 子句,它将继续更新它已经处理的分数,但如果你更新分数游戏已结束,您无需跟踪哪些游戏的分数已处理。
    • 所以在 game.id = "10" 我用 "$ID" 代替,对吗?我会回答约翰,是的! (假设您的“$ID”实际上是游戏桌的 id,而不是团队桌的 id,完全不同的东西)。不是批评,但一定要学习基本的 SQL,你很快就会感激的......
    • @Norman,为了扩展@virtualeyes,我建议您将变量命名为$game_id,这样就不会混淆您所指的id,您将自己垫在后面当你在 6 个月后查看你的代码时这样做,因为你已经忘记了所有那些现在在你脑海中如此清晰的细节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多