使用INNER JOIN将数字从一个表添加到另一个表 - 帮助!

时间:2011-06-28 16:46:44

标签: php sql join inner-join sql-update

我在网上浏览并发现类似于我想要的东西,但它没有执行...请帮助

我的表格具有以下结构:

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 g1.id = 1;

当我把它放在我的sql中时它会执行该函数但它不会改变我的'pointsfavor'和'pointscontra'字段来自团队...所以它说,受影响的行(0)......

查找

my current query

以下是我在游戏表格中输入的值(得分1&amp;得分2):

game table

这是我执行代码后的团队表...保持不变:

team table

请帮助。

2 个答案:

答案 0 :(得分:0)

使用左连接而不是内连接:

UPDATE team 
LEFT JOIN game g1 ON (team.id = g1.team1_id)
LEFT 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 g1.id = 1;

我不知道你的表字段是什么或你的代码是如何工作的,但我猜你的问题出在你的if语句中 例如,在第一次更新(pointsfavor)IF g1.score1&gt; g1.score2然后g1.score1 - g1.score2和第二个if,但在第二次更新时g1.score1&gt; g1.score2然后pointscontra + 0 + 0和下一个如果也做同样的事情 - 然后在这个查询中只是pointsfavor已经影响 因此,当第一个子句声明(pointsfavor)正确时,第二个子句的声明是不正确的! 看看你的代码agian;)

答案 1 :(得分:0)

两次更新(每个团队一次):

UPDATE team t1
SET t1.pointsfavor = t1.pointsfavor + IF(game.score1 > game.score2, game.score1 - game.score2, 0)
, t1.pointscontra = t1.pointscontra + IF(game.score2 > game.score1, game.score2 - game.score1, 0)
FROM team
INNER JOIN game ON game.team1_id=t1.id
WHERE game.id = 1

UPDATE team t2
SET t2.pointsfavor = t2.pointsfavor + IF(game.score2 > game.score1, game.score2 - game.score1, 0)
, t2.pointscontra = t2.pointscontra + IF(game.score1 > game.score2, game.score1 - game.score2, 0)    
FROM team
INNER JOIN game ON game.team2_id=t2.id
WHERE game.id = 1