MySQL 中日期和 BETWEEN 的奇怪之处
我正在运行一个查询来获取特定日期之间的行(本例中为当前日期和 7 天前)。
我尝试将其写为:
SELECT *
FROM faulttracker.ft_v_cases
WHERE DATE(cs_created) BETWEEN DATE(NOW()) AND DATE(NOW()-INTERVAL 7 DAY)
ORDER BY cs_created DESC;
但它返回 0 行。我不明白为什么它不起作用,我尝试将其重写为:
SELECT *
FROM faulttracker.ft_v_cases
WHERE DATE(cs_created) <= DATE(NOW())
AND DATE(cs_created) >= DATE(NOW()-INTERVAL 7 DAY)
ORDER BY cs_created DESC;
哪个确实起作用。
为什么第一个返回 0 行,但第二个按预期工作?据我所知,它们在功能上应该是等效的。
cs_created 是一个日期时间。
I'm running a query to get rows that fall between certain dates (the current date and 7 days ago for this example).
I tried writing it as:
SELECT *
FROM faulttracker.ft_v_cases
WHERE DATE(cs_created) BETWEEN DATE(NOW()) AND DATE(NOW()-INTERVAL 7 DAY)
ORDER BY cs_created DESC;
but it returned 0 rows. I couldn't understand why it didn't work, and I tried rewriting it as:
SELECT *
FROM faulttracker.ft_v_cases
WHERE DATE(cs_created) <= DATE(NOW())
AND DATE(cs_created) >= DATE(NOW()-INTERVAL 7 DAY)
ORDER BY cs_created DESC;
which DID work.
Why did the first one return 0 rows but the second one work as expected? As far as I can see they should be functionally equivalent.
cs_created is a datetime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据 文档,BETWEEN 期望以下内容格式:
在第一个示例中,您将最小值放在最后。
尝试使用:
According to the documentation, BETWEEN expects the following format:
In your first example, you are putting the min value last.
Try using:
我很确定您也可以使用:
这应该返回相同的结果,但也允许查询使用
cs_created
上的索引。I'm pretty sure you can just as well use:
This should return same results, but also allow the query to use index on
cs_created
.您的条件应该是 -
使用 Between 时,较低的日期值应位于左侧。
Your condition should be -
The lower date value should be on left side when using Between.
您必须始终将范围设置为
BETWEEN更小和更大
;无论您是否编写,处理都是相同的:因此,使用 BETWEEN 的代码需要编写为:
当然,这涵盖了过去 8 天,因为 BETWEEN/AND 的范围包含在内。
You must always have the range working as
BETWEEN smaller AND larger
; the treatment is the same regardless of whether you write:Hence, your code using BETWEEN needs to be written as:
That covers the last 8 days, of course, since the range with BETWEEN/AND is inclusive.
您是否尝试过这样写:
SELECT *
来自 failuretracker.ft_v_cases
CAST(NOW() AS DATE) 和 CAST(DATE(NOW()-INTERVAL 7 DAY) AS DATE) 之间的 CAST(cs_created AS DATE)
ORDER BY cs_created DESC;
手册状态:
have you tried putting it like this:
SELECT *
FROM faulttracker.ft_v_cases
WHERE CAST(cs_created AS DATE) BETWEEN CAST(NOW() AS DATE) AND CAST(DATE(NOW()-INTERVAL 7 DAY) AS DATE)
ORDER BY cs_created DESC;
the manual states: