Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql update multiple columns with same now()

I need to update 2 datetime columns, and I need them to be exactly the same, using mysql version 4.1.20. I'm using this query:

mysql> update table set last_update=now(), last_monitor=now() where id=1; 

It is safe or there is a chance that the columns are update with different time, because of the 2 visible calls to now()?
I don't think that it can be update with different values (I think internally mysql calls now() just once per row or something similar), but I'm not an expert, what do you think?

Update: Second question was extracted here.

like image 510
Radu Maris Avatar asked Sep 27 '10 08:09

Radu Maris


2 Answers

Found a solution:

mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1; 

I found this in MySQL Docs and after a few tests it works:

the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.

UPDATE t1 SET col1 = col1 + 1, col2 = col1;

like image 79
Radu Maris Avatar answered Oct 04 '22 08:10

Radu Maris


Mysql isn't very clever. When you want to use the same timestamp in multiple update or insert queries, you need to declare a variable.

When you use the now() function, the system will call the current timestamp every time you call it in another query.

like image 44
Olivier Avatar answered Oct 04 '22 09:10

Olivier