Comparing dates in MySQL ignoring time portion of

2020-02-20 06:41发布

I need to compare dates in MySQL ignoring the time portion in a DateTime column. I have tried the following SQL.

SELECT * FROM order_table where order_date=date_format('2012-05-03', '%Y-%m-%d');

It doesn't retrieve any row even though there is a date 2012-05-03 10:16:46 in MySQL table. How can the time portion in the DateTime field be ignored while comparing dates in MySQL?

8条回答
放荡不羁爱自由
2楼-- · 2020-02-20 07:06
SELECT * FROM order_table WHERE date(order_date) = '2012-05-03';
查看更多
走好不送
3楼-- · 2020-02-20 07:09

If you want to pass in a date then you can try something like this:

where YEAR(order_date)='2012' AND MONTH(order_date)='05' AND DAY(order_date)='03'

You can look at this for more functions.

查看更多
我只想做你的唯一
4楼-- · 2020-02-20 07:10

You could use the DATE function:

SELECT col1, col2, ..., coln
FROM order_table
WHERE date(order_date) = '2012-05-03'

But this is more efficient, if your table is large and you have an index on order date:

SELECT col1, col2, ..., coln
FROM order_table
WHERE order_date >= '2012-05-03'
AND order_date < '2012-05-04'
查看更多
Viruses.
5楼-- · 2020-02-20 07:11

Maybe, you can use function like date(). But in this case speed can be decreased, because index cannot be using. So, I recommend to use

SELECT * FROM order_table 
WHERE order_date between('2012-05-03 0:0:0' and '2012-05-03 23:59:59')
查看更多
戒情不戒烟
6楼-- · 2020-02-20 07:17

In my case i had , DATE_FORMAT and CONVERT_TZ

The only one worked for me is this

DATE_FORMAT(CONVERT_TZ(`order_item`.created, '+0:00', '+2:00'), '%d/%m/%Y %H:%i') 

BETWEEN 
('12/02/2018 01:42') 
AND 
('12/02/2018 10:51')
查看更多
女痞
7楼-- · 2020-02-20 07:26

This is bit old .... but a correct answer also is using the date_format at the column order_date like below:

SELECT * FROM order_table where date_format(order_date, '%Y-%m-%d')='2012-05-03';
查看更多
登录 后发表回答