首页 > 文章列表 > 如何查询MySQL中近一周的数据?

如何查询MySQL中近一周的数据?

mysql
424 2023-04-24

在mysql中,可以利用select语句查询近一周的数据,语法为“select * from table  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(column_time);”。

本教程操作环境:windows10系统、mysql8.0.22版本、Dell G3电脑。

mysql怎么查询近一周的数据

语法如下:

select * from table  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(column_time);

拓展知识:

查询一天:

select * from table where to_days(column_time) = to_days(now());
select * from table where date(column_time) = curdate();

查询一个月:

select * from table  where DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) <= date(column_time);

示例如下:

效果如图(这里SQL语句中的一周范围是指星期一到星期日,星期一为一周的第一天,因是8月11日查询的,所以只显示星期一到星期六的结果):

如何查询MySQL中近一周的数据?

日历:

如何查询MySQL中近一周的数据?

简单来说就是用今天的日期生成前七天的日期(利用union all命令),并根据星期一的日期条件刷选出本周的日期

        SELECT  DATE(subdate(curdate(),date_format(curdate(),'%w')-1)) as thisweek  
        union all  
        SELECT  DATE(DATE_ADD(subdate(curdate(),date_format(curdate(),'%w')-1), interval 1 day)) as thisweek  
        union all  
        SELECT  DATE(DATE_ADD(subdate(curdate(),date_format(curdate(),'%w')-1), interval 2 day)) as thisweek  
        union all  
        SELECT  DATE(DATE_ADD(subdate(curdate(),date_format(curdate(),'%w')-1), interval 3 day)) as thisweek  
        union all  
        SELECT  DATE(DATE_ADD(subdate(curdate(),date_format(curdate(),'%w')-1), interval 4 day)) as thisweek  
        union all  
        SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(),'%w')-1), interval 5 day)) as thisweek  
        union all  
        SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(),'%w')-1), interval 6 day)) as thisweek

如何查询MySQL中近一周的数据?

解析:

SELECT DATE(subdate(curdate(),date_format(curdate(),’%w’)-1))

得到的是这周的第一天(星期一到星期天为一周);也即8月6日