MySQL:仅在满足条件时更新字段

tnkciper  于 12个月前  发布在  Mysql
关注(0)|答案(6)|浏览(135)

是否可以在MySQL中执行UPDATE查询,仅在满足某些条件时才更新字段值?类似于:

UPDATE test
SET
    CASE
        WHEN true
        THEN field = 1
    END
WHERE id = 123

字符串
换句话说:

UPDATE test
SET
    something = 1,        /*field that always gets updated*/
    CASE
        WHEN true
        THEN field = 1    /*field that should only get updated when condition is met*/
    END
WHERE id = 123


什么是正确的方法来做到这一点?

szqfcxe2

szqfcxe21#

是的,我会的
这里有另一个例子:

UPDATE prices
SET final_price= CASE
   WHEN currency=1 THEN 0.81*final_price
   ELSE final_price
END

字符串
这是因为MySQL不会更新行,如果没有变化,as mentioned in docs
如果您将列设置为当前的值,MySQL会注意到这一点,并且不会更新它。

2ledvvac

2ledvvac2#

另一个解决方案,在我看来,更容易阅读是:

UPDATE test 
    SET something = 1, field = IF(condition is true, 1, field) 
    WHERE id = 123

字符串
如果条件满足,则将'field'设置为1(就像OP用作示例),如果不满足,则使用'field'的当前值。使用以前的值与不更改相同,所以就是这样。

n6lpvg4x

n6lpvg4x3#

试试这个:

UPDATE test
SET
   field = 1
WHERE id = 123 and condition

字符串

mhd8tkvw

mhd8tkvw4#

另一种解决方案我们可以使用MySQL IF()条件函数:

UPDATE test
SET  field  = IF(something == 1{CONDITION}, 1 {NEW VALUE}, field)
WHERE `id` = 5

字符串

jgwigjjp

jgwigjjp5#

另一种变体:

UPDATE test
SET field = IF ( {condition}, {new value}, field )
WHERE id = 123

字符串
仅当满足{condition}时,这将使用{new value}更新field

qeeaahzv

qeeaahzv6#

用AND条件找到解:

$trainstrength = "UPDATE user_character SET strength_trains = strength_trains + 1, trained_strength = trained_strength +1, character_gold = character_gold - $gold_to_next_strength WHERE ID = $currentUser AND character_gold > $gold_to_next_strength";

字符串

相关问题