开发者

MySQL date_add() doesn't work in WHERE clause?

开发者 https://www.devze.com 2023-01-23 07:12 出处:网络
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\'))

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 wo开发者_JAVA百科rk?

Thanks much


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)


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)


You compare DateTime (result of DATE_ADD) with DATE. You need WHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR))


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 -- thedate` values need to match that exactly to be returned.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消