gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:55:11 30 4
gpt4 key购买 nike

是否可以在 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

这样做的正确方法是什么?

最佳答案

是的!

这里有另一个例子:

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

这是因为 MySQL 不会更新行,如果没有变化,as mentioned in docs :

If you set a column to the value it currently has, MySQL notices this and does not update it.

关于MySQL:仅在满足条件时更新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893355/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com