1.背景
在实际项目中,我们会遇到分布式定时任务执行的情况。有时在执行定时任务时,如果查询的数据量比较大,我们会选择执行前几天过滤的数据。
[En]
In the actual project, we will encounter the situation of distributed timing task execution. Sometimes when the timing task is executed, if the amount of data queried is relatively large, we will choose to execute the data filtered several days ago.
避免执行全量的数据导致内存占用过大或执行时间过长导致OOM等问题。
这里我们就会用到SQL来过滤当前时间间隔1天或几天的查询。
1.1.查询SQL语句
这里用到一张talk_course表作为查询sql语句的执行表单,表的字段如下:
表中大致有以下测试数据:
[En]
There are roughly the following test data in the table:
查询距离当前执行时间前一天的SQL语句如下:
查询距离当前时间前1天的数据
SELECT * FROM talk_course
t
WHERE t.createTime NOW()
AND t.createTime >= date_sub(now(), interval 1 day);
查询结果:
查询当前时间前一天的时间:
[En]
Query the time of the day before the current time:
查询当前时间前一天的时间<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>Query the time of the day before the current time</font>*</details>
SELECT date_sub(now(),interval 1 day) as yesterday
1.2.查询语句分析
这里用到了两个函数:
DATE_ADD(date,INTERVAL expr unit)
DATE_SUB(date,INTERVAL expr unit)
DATE_ADD() 函数向日期添加指定的时间间隔。
DATE_SUB() 函数向日期减少指定的时间间隔。
其中 expr 参数是您希望添加的时间间隔。
type 参数可以是下列值:
Type 值 MICROSECOND SECOND MINUTE HOUR DAY WEEK MONTH QUARTER YEAR SECOND_MICROSECOND MINUTE_MICROSECOND MINUTE_SECOND HOUR_MICROSECOND HOUR_SECOND HOUR_MINUTE DAY_MICROSECOND DAY_SECOND DAY_MINUTE DAY_HOUR YEAR_MONTH
Original: https://www.cnblogs.com/yif0118/p/15659617.html
Author: 人无名,则可专心练剑
Title: 【数据库】 — MySQL中查询当前时间间隔前1天的数据
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/507974/
转载文章受原作者版权保护。转载请注明原作者出处!