这是另一个问题的后续行动 Compare 2 columns, then perform action on another column in MySQL
我在MySQL中有一个名为TableX的表。 TableX中有4列。列是ColumnCompare_Now,ColumnCompare_Past,ColumnNumber_Now,ColumnNumber_Past。
我想编写一个具有以下逻辑的MySQL UPDATE语句;
If ColumnCompare_Now == 'ActionNeeded' and ColumnCompare_Past == 'ActionNeeded',
then ColumnNumber_Now = `ColumnNumber_Now` + `ColumnNumber_Past`
else if ColumnCompare_Now == 'ActionNeeded' and ColumnCompare_Past != 'ActionNeeded'
then ColumnNumber_Now = `ColumnNumber_Now` - `ColumnNumber_Past`
如何在MySQl中处理else if语句?
答案 0 :(得分:2)
对于条件更新,您可以使用case
update
TableX
set
ColumnNumber_Now =
case
when ColumnCompare_Now = 'ActionNeeded' and ColumnCompare_Past = 'ActionNeeded'
then `ColumnNumber_Now` + `ColumnNumber_Past`
when ColumnCompare_Now = 'ActionNeeded' and ColumnCompare_Past != 'ActionNeeded'
then `ColumnNumber_Now` - `ColumnNumber_Past`
end