首页 > 解决方案 > 从下周获得物品

问题描述

我开始做一个查询,例如:

SELECT * 
FROM mytable
WHERE (weekofyear(now())+1) <= date_inserted < weekofyear(now()+2)

这样做的问题是,前几年的项目也会出现在这里。执行此查询的最佳方法是什么-我希望我仍然可以在date_inserted字段上的查询中使用索引,这就是我在这里问这个的原因

标签: mysqlsqldatequery-optimizationwhere-clause

解决方案


我将其表述为:

where
        date_inserted >=  current_date + interval 7 - weekday(current_date) day
    and date_inserted <  current_date + interval 14 - weekday(current_date) day

表达式current_date + interval 7 - weekday(current_date) day为您提供下周的第一天。这在假设您的周从星期一开始的假设下有效。

您可以看到列上没有应用日期函数date_inserted,这意味着 MySQL 很乐意使用该列上的索引进行过滤(如果有的话)。


推荐阅读