比较mysql表并更新值

时间:2014-04-23 18:07:21

标签: mysql function compare

我想比较mysql上2个类似表的实际结果和预测。

 id | data1| data2 | 

用户

 id | data1| data2 | points

 id | user| total points

我想做以下事情:

 if (real.data1 = user.data1) AND (real.data2 = user.data2)
 update user set points=8 where id=1
 else if(real.data1 > user.data1) AND (real.data2 > user.data2)
 update user set points=4 where id=1
 else if (real.data1 = real.data2) AND (user.data1 = user.data2)
 update user set points=4 where id=1
  else if (real.data1 < user.data1) AND (real.data2 < user.data2)
  update user set points=4 where id=1
        else
            update user set points=0 where id=1      
   sum all values from points and update ranking table

有可能吗?

1 个答案:

答案 0 :(得分:0)

我相信以下内容适用于您问题的前半部分,但我没有对其进行测试:

UPDATE `user` u
 INNER JOIN `real` r ON (u.id = r.id)
SET    u.points = IF(r.data1 = u.data1 and r.data2 = u.data2,
                     8,
                     IF(r.data1 > u.data1 and r.data2 > u.data2,
                        4,
                        IF(r.data1 = r.data2 and u.data1 = u.data2,
                           4,
                           IF(r.data1 < u.data1 and r.data2 < u.data2,
                              4,
                              0)
                          )
                       )
                    )

如果没有意义,请参阅有关IF语句的MySQL docs