简体   繁体   English

SQL查询中具有多个字段的IF语句

[英]IF statement in Sql query with multiple fields

What I'm trying to accomplish is this - update the table with certain values only IF the high-score is better than the current one. 我要完成的工作是-仅当高分比当前高时才用某些值更新表。

Got table with columns userId , highScore , something , dateLastPlayed 有列userIdhighScoresomethingdateLastPlayed的表

User with userId of 1 has beaten his own score, and in that case I want to update all the fields in the row. userId为1的用户已经打败了自己的分数,在这种情况下,我想更新该行中的所有字段。 If he has not beaten his own high-score, I just want to update the dateLastPlayed field. 如果他没有超过自己的高分,我只想更新dateLastPlayed字段。

This is how I insert stuff so far 到目前为止,这是我插入内容的方式

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

Note that userId has unique key. 请注意,userId具有唯一键。

This works fine but this updates highScore , something and dateLastPlayed fields every time. 这可以正常工作,但是每次都会更新highScoresomethingdateLastPlayed字段。 I want to update fields highScore and something only IF the variable $highScore is greater than what is current set in the database. 我想更新领域的高分只有当变量$高分是比什么是数据库中的当前设置值。

I have read the MySQL docs but I do not quite get it. 我已经阅读了MySQL文档,但我不太了解。 How can I accomplish this? 我该怎么做? Note that I could do this using multiple queries and fetching data and then make more queries using that data, but I feel that is simply not the way to go and that it would take literally seconds for you guys to come up with a brilliant way to tackle the problem. 请注意,我可以使用多个查询并提取数据来进行此操作,然后使用该数据进行更多查询,但是我觉得这根本不是路要走,而且你们花了几秒钟的时间才能找到一种绝妙的方法解决问题。

Many thanks! 非常感谢!

If you want to do it in one SQL, it'll be something along the lines of: 如果要在一个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'

The disadvantage of this compared to multiple statements would be that the business logic is on the database / SQL side. 与多条语句相比,此方法的缺点是业务逻辑位于数据库/ SQL端。 Personally I prefer to keep business logic in the code, all in one place, for easier maintenance later. 就我个人而言,我更喜欢将业务逻辑保留在代码中,全部放在一个地方,以便以后进行维护。

Add a condition to the WHERE clause: 在WHERE子句中添加一个条件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM