以下查询不返回结束日期(4 月 20 日)的记录。我在某处读到它,因为传递给查询的日期没有考虑时间。但是在研究了各种解决方案之后,我似乎无法为 MySQL 弄清楚。
select * from listings
where created_date >= '2020-04-18'
and created_date <= '2020-04-20'
created_date 是一个日期时间字段。
请注意,在这种情况下,我不能使用“介于”。
因为created_date是 a DATETIME,所以它的时间部分可能不为零。当您将它与没有时间部分的日期进行比较时,该日期的时间部分设置为 0,因此测试失败。您需要最好使用:
created_date < '2020-04-21'
或者您可以包括时间部分,但这会减慢比较速度:
created_date <= '2020-04-20 23:59:59'
或者,参加DATE并进行比较,但这有防止在 上使用索引的缺点created_date:
DATE(created_date) <= '2020-04-20'
最好的逻辑是:
where created_date >= '2020-04-18' and
created_date < '2020-04-21'
或者,如果您愿意:
where created_date >= '2020-04-18' and
created_date < date('2020-04-20') + interval 1 day
这些是索引和优化器安全的,因为列上没有函数。无论是否有时间组件,它们都可以工作。