2013-10-10 46 views
0

我想要完成的是这个 - 只用某些值更新表,如果高分比当前更好。在多个字段的Sql查询中的IF语句

了表列用户id高分东西dateLastPlayed

用户与用户id的1击败了自己的成绩,而在这种情况下,我想更新所有行中的字段。如果他没有击败他自己的高分,我只想更新dateLastPlayed字段。

这是我的东西插入到目前为止

INSERT INTO table VALUES ('$userId', '$highScore', '$something', '$dateLastPlayed') ON DUPLICATE KEY UPDATE highScore='$highScore', something='$something', dateLastPlayed='$dateLastPlayed' 

注意,用户标识具有唯一键。

这工作得很好,但是这个更新高分东西,每次dateLastPlayed领域。 我想更新字段highScore东西只有如果变量$ highScore大于当前在数据库中设置的值。

我已经阅读了MySQL文档,但我不太明白。 我该如何做到这一点?请注意,我可以使用多个查询并获取数据来做到这一点,然后使用这些数据进行更多查询,但我认为这不是一种好的方法,而且这需要几秒钟的时间才能为您提供一种绝妙的方式解决问题。

非常感谢!

+0

检查: INSERT ... ON与其中http重复键UPDATE://stackoverflow.com/questions/2469457/insert-on-duplicate-key-update-with-where – mucio

回答

1

如果你想要做一个SQL,它会沿着线的东西:

INSERT INTO table VALUES ('$userId', '$highScore', '$something', '$dateLastPlayed') 
ON DUPLICATE KEY 
UPDATE 
    highScore= 
     case 
      when highScore >= $highScore then highScore 
      else '$highScore' 
     end, 
    something= 
     case 
      when highScore >= $highScore then something 
      else '$something' 
     end, 
    dateLastPlayed ='$dateLastPlayed' 

此方法的缺点与多个语句相比,业务逻辑位于数据库/ SQL端。我个人更喜欢将代码中的业务逻辑集中在一个地方,以便以后更轻松地进行维护。

+0

明天要试一下,似乎是合理的。非常感谢! –

+0

+1相当不错的查询 – Bohemian

0

添加条件WHERE子句:

update mytable set 
highScore = $highScore, 
something = $something 
where userid = $userid 
and highScore < $highScore -- only update if new high score exceeds existing 
+0

的事情是我有使用INSERT和ON DUPLICATE KEY,而不是UPDATE查询本身。感谢您的帮助。 –