MySql查询某个时间段内的数据实例(前一周、前三个月、前一年等)
作者:晤卉 时间:2024-01-18 09:36:31
1、使用函数DATE_SUB
DATE_SUB函数在当前时间减去一定的时间
DATE_SUB(date,INTERVAL expr unit)
date:合法日期,可以是当前时间now()
expr:希望减去的时间,整数
unit:减去时间的单位,如day,week,month,year
实例:
u_user表
(1)、前一周的数据
当前时间:
sql:
select * from u_user where u_create_time > DATE_SUB(NOW(),INTERVAL 7 day);
结果:
另一种sql写法:
select * from u_user where u_create_time > DATE_SUB(NOW(),INTERVAL 1 WEEK);
(2)、前三个月的数据
sql:
select * from u_user where u_create_time > DATE_SUB(NOW(),INTERVAL 3 MONTH);
结果:
(3)、前一年的数据
sql:
select * from u_user where u_create_time > DATE_SUB(NOW(),INTERVAL 1 YEAR);
结果:
2、使用函数DATE_ADD
DATE_ADD函数在当前时间加上一定的时间
DATE_ADD(date,INTERVAL expr unitda
date:合法日期,可以是当前时间now(),也可以是表中的时间字段
expr:希望加上的时间,整数
unit:加上时间的单位,如day,week,month,year
实例:
(1)、前一周的数据
sql:
select * from u_user where DATE_ADD(u_create_time,INTERVAL 7 DAY) > NOW();
结果:
(2)、前三个月的数据
sql:
select * from u_user where DATE_ADD(u_create_time,INTERVAL 3 MONTH) > NOW();
结果:
(3)、前一年的数据
sql:
select * from u_user where DATE_ADD(u_create_time,INTERVAL 1 YEAR) > NOW();
结果:
来源:https://blog.csdn.net/weixin_46112857/article/details/124575966
标签:mysql,查询,时间段
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析
2023-09-16 04:58:30
![](https://img.aspxhome.com/file/2023/7/70237_0s.png)
go slice 数组和切片使用区别示例解析
2023-06-22 04:07:16
![](https://img.aspxhome.com/file/2023/0/87610_0s.jpg)
利用python库matplotlib绘制不同的图表
2022-11-06 18:08:16
![](https://img.aspxhome.com/file/2023/4/108144_0s.png)
白鸦:如何设计用户体验?
2008-01-03 16:53:00
基于Python实现简易文档格式转换器
2021-12-12 14:32:31
![](https://img.aspxhome.com/file/2023/9/69549_0s.png)
Python 的 f-string 可以连接字符串与数字的原因解析
2023-08-21 15:34:41
![](https://img.aspxhome.com/file/2023/8/70098_0s.png)
python 列表,集合和字典的增删改查
2021-06-20 04:31:37
浅谈PL/SQL批处理语句:BULK COLLECT与FORALL对优化做出的贡献
2024-01-14 01:04:27
![](https://img.aspxhome.com/file/2023/5/64845_0s.png)
使用python批量修改文件名的方法(视频合并时)
2022-08-24 13:19:07
![](https://img.aspxhome.com/file/2023/8/127828_0s.png)
MongoDB的基本特性与内部构造的讲解
2024-01-13 21:02:55
![](https://img.aspxhome.com/file/2023/5/93645_0s.png)
Python接入MySQL实现增删改查的实战记录
2023-08-23 04:52:50
python使用pandas读xlsx文件的实现
2021-01-21 05:00:10
![](https://img.aspxhome.com/file/2023/9/79669_0s.jpg)
python使用多线程不断刷新网页的方法
2022-10-03 09:19:26
一文教你如何快速学会Go的struct数据类型
2024-02-14 22:58:44
python tkinter canvas使用实例
2021-07-11 23:49:50
![](https://img.aspxhome.com/file/2023/7/90837_0s.png)
Django如何实现上传图片功能
2023-04-23 17:35:01
![](https://img.aspxhome.com/file/2023/8/90608_0s.png)
Golang 利用反射对结构体优雅排序的操作方法
2024-05-10 13:56:42
![](https://img.aspxhome.com/file/2023/9/127489_0s.png)
Mysql分库分表之后主键处理的几种方法
2024-01-20 21:00:09
![](https://img.aspxhome.com/file/2023/8/128438_0s.png)
ASP短日期格式为长日期
2009-06-11 12:53:00
Python函数式编程指南(四):生成器详解
2023-08-23 05:50:02