在MySQL的学习过程中,最复杂,最考验SQL功底的就是SELECT查询语句了。下面总结一下在WEB网站开发中比较实用的时期查询SQL语句。假设MySQL数据库表中时间字段为add_time,类型为datetime。
1、查询当天
SELECT * FROM `article` WHERE to_days(`add_time`) = to_days(now());
2、查询昨天
SELECT * FROM `article` WHERE to_days(now()) – to_days(`add_time`) = 1;
3、查询最近7天
SELECT * FROM `article` WHERE date_sub(curdate(), INTERVAL 7 DAY) <= DATE(`add_time`);
或者
SELECT * FROM `article` WHERE curdate()- INTERVAL 7 DAY <= DATE(`add_time`);
4、查询最近30天
SELECT * FROM `article` WHERE date_sub(curdate(), INTERVAL 30 DAY) <= DATE(`add_time`);
或者
SELECT * FROM `article` WHERE curdate()-INTERVAL 30 DAY <= DATE(`add_time`);
5、查询截止到当前本周
SELECT * FROM `article` WHERE YEARWEEK(date_format(`add_time`,'%Y-%m-%d')) = YEARWEEK(now());#默认从周日开始到周六
SELECT * FROM `article` WHERE YEARWEEK(date_format(`add_time`,'%Y-%m-%d'),1) = YEARWEEK(now(),1);#设置为从周一开始到周日
6、查询上周的数据
SELECT * FROM `article` WHERE YEARWEEK(date_format(`add_time`,'%Y-%m-%d')) = YEARWEEK(now())-1;
7、查询截止到当前本月
SELECT * FROM `article` WHERE date_format(`add_time`, '%Y%m') = date_format(curdate() , '%Y%m');
8、查询上一月
SELECT * FROM `article` WHERE period_diff(date_format(now() , '%Y%m') , date_format(`add_time`, '%Y%m')) =1;
MySQL常用的日期SQL查询语句
最新推荐文章于 2021-02-07 15:45:32 发布