Как в операторе SQL сравнить дату, сохраненную как TIMESTAMP, с датой в формате ГГГГ-ММ-ДД?
SELECT * FROM table WHERE timestamp = '2012-05-05'
Я хочу, чтобы этот запрос возвращал все строки с меткой времени в указанный день, но он возвращал только строки с меткой времени в полночь.
As suggested by some, by using
DATE(timestamp)you are applying manipulation to the column and therefore you cannot rely on the index ordering.
BETWEENwould only be reliable if you include the milliseconds. In the example timestamp
BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59'you exclude records with a timestamp between
2012-05-05 23:59:59.999. However, even this method has some problems, because of the datatypes precision. Occasionally 999 milliseconds is rounded up.
The best thing to do is:
Use a conversion function of MYSQL :
This should work
As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as
CURRENT_DATE(). This WILL use the index on the log_timestamp column.
I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:
Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.
In case you are using SQL parameters to run the query then this would be helpful
When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way: