问题
When I try to run the following query:
... WHERE `date` = DATE_ADD(NOW(), INTERVAL 10 HOUR)
It doesn't work, so I have to use the $date = date("Y-m-d", strtotime('+10 hours'))
But why date_add
doesn't work?
Thanks much
回答1:
Note that DATE_ADD() function returns a time part in addition to the date. This is not the same as using php's date("Y-m-d", strtotime('+10 hours'))
, which only returns the date part.
SELECT DATE_ADD(NOW(), INTERVAL 10 HOUR);
+-----------------------------------+
| DATE_ADD(NOW(), INTERVAL 10 HOUR) |
+-----------------------------------+
| 2010-11-05 01:59:51 |
+-----------------------------------+
1 row in set (0.00 sec)
You could use WHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR))
instead:
SELECT DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR));
+-----------------------------------------+
| DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR)) |
+-----------------------------------------+
| 2010-11-05 |
+-----------------------------------------+
1 row in set (0.02 sec)
Test case:
CREATE TABLE tbl (id int, date datetime);
INSERT INTO tbl VALUES (1, '2010-11-04');
INSERT INTO tbl VALUES (2, '2010-11-05');
INSERT INTO tbl VALUES (3, '2010-11-06');
INSERT INTO tbl VALUES (4, '2010-11-07');
SELECT * FROM tbl WHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR));
+------+---------------------+
| id | date |
+------+---------------------+
| 2 | 2010-11-05 00:00:00 |
+------+---------------------+
1 row in set (0.00 sec)
回答2:
NOW()
is a timestamp, not a date.
Example:
mysql> select now(), current_date();
+---------------------+----------------+
| now() | current_Date() |
+---------------------+----------------+
| 2010-11-04 12:00:01 | 2010-11-04 |
+---------------------+----------------+
I think this is what you want:
... WHERE date = DATE_ADD(CURRENT_DATE(), INTERVAL 10 HOUR)
回答3:
You compare DateTime (result of DATE_ADD
) with DATE. You need WHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR))
回答4:
This:
WHERE date = DATE_ADD(NOW(), INTERVAL 10 HOUR)
...does work (assuming date
is DATETIME), but it includes the time portion when the statement was executed -- the
date` values need to match that exactly to be returned.
回答5:
I know this is answered already but there is a better solution in this usecase:
DATE_ADD(TODAY(), INTERVAL 10 HOUR)
This removes one additional operation because TODAY
returns date without time part.
来源:https://stackoverflow.com/questions/4098539/mysql-date-add-doesnt-work-in-where-clause