Is it possible to use IF(cond1 AND cond2,result,else result) in MySQL?

江枫思渺然 提交于 2019-12-24 11:37:20

问题


I want to do update query if the consecutive 5 column have 0 value. My first idea is:

UPDATE `table_name` 
SET `count` = IF(`col1`=0.00 AND 
                 `col2`=0.00 AND 
                 `col3`=0.00 AND 
                 `col4`=0.00 AND 
                 `col5`=0.00,  count+1, count)

But I think using AND in IF condition isn't work. Any idea? Thanks before


回答1:


Using AND in an IF is perfectly valid, but as Grijesh suggets, using the condition in the WHERE clause is the usual way to do it.

Your query though shouldn't give any errors.




回答2:


I think you need this, if I am not wrong, it looks simple to me:

UPDATE `table_name` 
SET    `count`= `count` + 1
WHERE  `col1`=0.00 AND `col2`=0.00 AND 
       `col3`=0.00 AND `col4`=0.00 AND 
       `col5`=0.00;

Edit

And what @Bart Friederichs 's answer is correct AND/OR are valid in if()

IF() works like: ( IF() function )

IF(<condition>, <value if true>, <value if false>)  

I perform below experiment, And according to this I believe your query will work. (Its just my idea, I am not sure)

mysql> SET  @a=IF(0 AND 1,5,3);
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @a;
+------+
| @a   |
+------+
|    3 |
+------+
1 row in set (0.00 sec)

NOTE: You can do = and you can use AND/OR in IF() function.



来源:https://stackoverflow.com/questions/15828697/is-it-possible-to-use-ifcond1-and-cond2-result-else-result-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!