|
|
|
|
| MySQL: Comparing datetime columns |
|
Problem: The column type 'datetime' can be a real time-saver, but selecting records of a certain age can be tricky.
|
|
Solution: First of all, make 100% sure time is perfectly syncronized between the mysql server and its clients.
SUBDATE() only accepts datetime objects or the INTERVAL keyword:
"SELECT * FROM table WHERE column BETWEEN SUBDATE(NOW(), INTERVAL 7 DAY) AND NOW()"
The INTERVAL keyword accepts one (and only one) of the following: YEAR, MONTH, DAY, HOUR, MINUTE and SECOND.
SUBTIME on the other hand lets you specify the time as a string:
"SELECT * FROM table WHERE column BETWEEN SUBTIME(NOW(), '7 0:0:0.0000') AND NOW();"
This allows more fine-grained control but can't express months or years.
Note: While you COULD reverse the expression like so;
"SUBDATE(column, INTERVAL 7 DAY)"
but this would be a BIG MISTAKE because you would make one expensive SUBDATE() call for every single record. The SUBDATE(NOW(),...) expression needs only be called once.
Finally, resist the temptation to use > and < for datetime comparison. The documentation does in fact explain that this is possible because of silent conversion between string and numerical form. Unfortunately, in real life it doesn't work as expected. If you really must use comparison instead of the excellent BETWEEN...AND form, then I suggest you first convert to unixtime.
|
|
|
|
|
|
This is free technical advice without any warranties.
Use at your own risk. Solutions offered may not apply to your particular problem at all.
Opinions and views expressed in the articles are the authors' personal
and may not necessarily reflect or coincide with those of Ano-Tech Computers.
We take no responsibility if anything bad happens from following any of
the intructions given. If you don't understand and accept this, please
contact us for personal assistance instead.
To read our full disclaimer, go
here.
We welcome anyone who is willing to contribute to this public knowledge base,
contact siteadmin@atc.no
if you have information you would like to share. The idea is not to replace
the commercial support sites, but to publish those hard-to-find
solutions you've found yourself looking for over and over again.
Show all articles