Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Update field of set IF NULL or other value

Tags:

mysql

I am currently using two update queries and am wondering if there is a way to cut it down to one.

field1 OFTYPE INT field2 OFTYPE DATETIME field3 OFTYPE DATETIME  UPDATE `Table1` SET `field1` = `field1` + 1, `field2` = NOW() WHERE `id` = $id; UPDATE `Table1` SET `field3` = NOW() WHERE `id` = $id AND (`field3` < '2011-00-00 00:00:00' OR `field3` IS NULL); 

I'm trying to get a query that would do the UPDATE more like so:

UPDATE `Table1`  SET `field1` = `field1` + 1,     `field2` = NOW(),     `field3` = ISNULL(NOW(), `first_seen`); 
like image 912
wachpwnski Avatar asked Mar 13 '12 19:03

wachpwnski


1 Answers

I think that's it's possible for you to do this using an IF statement. The IF statement takes 3 parameters when you're using it: the expression, value if true, value if false

So in your case, you could probably write your queries in one go like the following:

UPDATE Table1  SET      field1 = field1 + 1,      field2 = NOW(),     field3 = IF(field3 < '2011-00-00 00:00:00' OR field3 IS NULL, NOW(), field3) WHERE id = $id; 

This way, if expression is true, then field3 will be NOW() and otherwise, it'll remain as it was.

like image 62
MysticXG Avatar answered Sep 28 '22 01:09

MysticXG