mysql sql if then_如何在MySQL更新查询中使用If Then Else?

bd96500e110b49cbb3cd949968f18be7.png

I want to update a table in MySQL like this:

UPDATE Table

SET A = '20' IF A > 20

SET A = A IF A < 20

SET A = 0 IF A <= 1

WHERE A IS NOT NULL;

But the above SQL is not valid Syntax. I also tried this:

UPDATE table

SET A = IF(A > 20, 20, IF(A < 20, A, 0));

But is also invalid Syntax. How do I use an if statement in an update query like this?

解决方案

I think you were 99% there:

UPDATE table

SET A = IF(A > 20, 20, IF(A < 20 && A > 1, A, 0))

WHERE A IS NOT NULL;

Add the && A > 1 to the second IF statement and your third condition is satisfied.

Edit:

Per @Andre's comment to the question and the suggestion that the nested IF is difficult to read, you could also do this as a couple of queries that don't do any unnecessary work and are readable:

UPDATE table SET A = 20 WHERE A > 20;

UPDATE table SET A = 0 WHERE A <= 1;

When A is NULL, it will not meet either of these conditions, and thus eliminates the need to specify that A not be NULL.

Next, there's no need for the third condition as @Andre suggested. If A is between 1 and 20, it gets left as-is.

Finally, setting A to 0 where A is less than or equal to 1 seems unusual. Values of 1 will be changed to 0. If you intend to simply set values less than 1 (including negative values) to 0, then you should swap < for <=.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值