MySQL SET IF 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5851259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:43:34  来源:igfitidea点击:

MySQL SET IF Statement

mysqlif-statement

提问by H. Ferrence

Can someone show me the correct mysql syntax to do the following:

有人可以向我展示正确的 mysql 语法来执行以下操作:

Update a column in a table with 1 of 3 values:

使用 3 个值之一更新表中的列:

If col_A = 4 set col_Z to col_A If col_B = 4 set col_Z to col_B Else set col_Z to NULL (or leave alone because col_Z is initialized to NULL)

如果 col_A = 4 将 col_Z 设置为 col_A 如果 col_B = 4 将 col_Z 设置为 col_B 否则将 col_Z 设置为 NULL(或者不理会因为 col_Z 被初始化为 NULL)

Here's what I have:

这是我所拥有的:

Update my_table
SET col_Z = IF(col_A = 4, col_A, IF(col_B = 4, col_B, NULL))
WHERE id = "001"

IS this correct?

这样对吗?

回答by Johan

Yes, it looks correct.

是的,它看起来是正确的。

The following code will be simpler though.

不过下面的代码会更简单。

UPDATE my_table
SET col_Z = IF(col_A = 4 OR col_B = 4, 4, NULL)
WHERE id = "001"