MySQL: Strange result when subtracting Date value and NOW()
I just tried to insert two rows with the current datetime and then calculated the elapsed time since that date. Here are the rows from my table after two insertions and using NOW() function to set the timestamp:
mysql> select * from pendingActivations;
+--------+------------+---------------------+
| userId | code | timestamp |
+--------+------------+---------------------+
| 2 | aaa | 2010-08-23 17:04:02 |
| 2345 | alkfjkla23 | 2010-08-23 16:59:53 |
+--------+------------+---------------------+
Few minutes after the insertion of the row with userId equal to 2, I executed the following command which I hoped would give me the elapsed time from the timestamp for each row. Here are the results:
mysql> select userId, code, timestamp, NOW() - timestamp as elapsedSeconds from pendingActivations;
+--------+------------+---------------------+----------------+
| userId | code | timestamp | elapsedSeconds |
+--------+------------+---------------------+----------------+
| 2 | aaa | 2010-08-23 17:04:02 | 136.000000 |
| 2345 | alkfjkla23 | 2010-08-23 16:59:53 | 4585.000000 |
+--------+------------+---------------------+----------------+
I wonder how the second ro开发者_开发技巧w has that huge elapsedSeconds value which indicates that exactly 1 hour, 16 minutes and 25 seconds had passed, although it is easily seen that just around 5 minutes had passed since.
Here is the table structure:
mysql> describe pendingActivations;
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| userId | int(11) | NO | PRI | NULL | |
| code | varchar(32) | NO | UNI | NULL | |
| timestamp | datetime | NO | | NULL | |
+-----------+-------------+------+-----+---------+-------+
Any ideas and/or explanations?
I can't explain the issue, but I suspect the -
operation returns the result in an unexpected format (maybe including microseconds or tenths?)
I would use TIMEDIFF()
.
returns
expr1
–expr2
expressed as a time value. expr1 and expr2 are time or date-and-time expressions, but both must be of the same type.
精彩评论