登录
首页 >  数据库 >  MySQL

Mysql日期查询的详细介绍

来源:脚本之家

时间:2023-01-28 08:53:52 223浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Mysql日期查询的详细介绍》,聊聊时间、日期、Mysql查询,我们一起来看看吧!

查询当前日期

SELECT CURRENT_DATE();
SELECT CURDATE();

查询当前日期和时间

SELECT NOW();

查询今天的数据

SELECT * FROM `表名` WHERE TO_DAYS(NOW()) = TO_DAYS(`字段`);
SELECT * FROM `表名` WHERE TO_DAYS(NOW()) - TO_DAYS(`字段`) = 0;

查询昨天的数据

SELECT * FROM ``表名`` WHERE TO_DAYS(`字段`) = TO_DAYS(NOW()) -1;
SELECT * FROM ``表名`` WHERE TO_DAYS(`字段`) - TO_DAYS(NOW()) = -1;
SELECT * FROM ``表名`` WHERE TO_DAYS(NOW()) = TO_DAYS(`字段`) +1;
SELECT * FROM ``表名`` WHERE TO_DAYS(NOW()) - TO_DAYS(`字段`) = 1;

查询最近七天的数据

SELECT * FROM `表名` WHERE DATE_SUB(CURDATE(),INTERVAL 7 DAY) 

查询最近三十天的数据

SELECT * FROM table WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) 

查询本周的数据

SELECT * FROM `表名` WHERE YEARWEEK(date_format(`字段`,'%Y-%m-%d')) = YEARWEEK(CURDATE());
SELECT * FROM `表名` WHERE YEARWEEK(date_format(`字段`,'%Y-%m-%d')) - YEARWEEK(CURDATE()) = 0;
SELECT * FROM `表名` WHERE YEARWEEK(DATE_FORMAT(`字段`,'%Y-%m-%d')) = YEARWEEK(DATE_FORMAT(CURDATE(),'%Y-%m-%d'));
SELECT * FROM `表名` WHERE YEARWEEK(DATE_FORMAT(`字段`,'%Y-%m-%d')) - YEARWEEK(DATE_FORMAT(CURDATE(),'%Y-%m-%d')) = 0;

查询上周的数据

SELECT * FROM `表名` WHERE YEARWEEK(DATE_FORMAT(`字段`,'%Y-%m-%d')) = YEARWEEK(DATE_FORMAT(CURDATE(),'%Y-%m-%d')) - 1;
SELECT * FROM `表名` WHERE YEARWEEK(DATE_FORMAT(`字段`,'%Y-%m-%d')) - YEARWEEK(DATE_FORMAT(CURDATE(),'%Y-%m-%d')) = -1;
SELECT * FROM `表名` WHERE YEARWEEK(DATE_FORMAT(`字段`,'%Y-%m-%d')) = YEARWEEK(CURDATE()) - 1;
SELECT * FROM `表名` WHERE YEARWEEK(DATE_FORMAT(`字段`,'%Y-%m-%d')) - YEARWEEK(CURDATE()) = -1;

查询当月的数据

SELECT * FROM `表名` WHERE DATE_FORMAT(`字段`,'%Y-%m') = DATE_FORMAT(CURDATE(),'%Y-%m');
SELECT * FROM `表名` WHERE MONTH(`字段`) - MONTH(NOW()) = 0;
SELECT * FROM `表名` WHERE MONTH(`字段`) = MONTH(NOW());

查询上月的数据

SELECT * FROM `表名` WHERE DATE_FORMAT(`字段`,'%Y-%m') = DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 MONTH),'%Y-%m');

查询本季度的数据

SELECT * FROM `表名` WHERE QUARTER(`字段`) = QUARTER(NOW()) AND YEAR(`字段`) = YEAR(NOW());

查询上季度的数据

SELECT * FROM `表名` WHERE QUARTER(`字段`) = QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER)) AND YEAR(`字段`) = YEAR(NOW());

查询上半年(六个月)的数据

SELECT * FROM `表名` WHERE `字段` BETWEEN DATE_SUB(NOW(),INTERVAL 6 MONTH) AND NOW();

查询今年的数据

SELECT * FROM `表名` WHERE DATE_FORMAT(`字段`,'%Y') = DATE_FORMAT(NOW(),'%Y');
SELECT * FROM `表名` WHERE DATE_FORMAT(`字段`,'%Y') - DATE_FORMAT(NOW(),'%Y') = 0;
SELECT * FROM `表名` WHERE YEAR(NOW()) = YEAR(`字段`);
SELECT * FROM `表名` WHERE YEAR(NOW()) - YEAR(`字段`) =0;

查询去年的数据

SELECT * FROM `表名` WHERE DATE_FORMAT(`字段`,'%Y') - DATE_FORMAT(NOW(),'%Y') = -1;
SELECT * FROM `表名` WHERE YEAR(NOW()) = YEAR(`字段`) + 1;
SELECT * FROM `表名` WHERE YEAR(NOW()) - YEAR(`字段`) = 1;

终于介绍完啦!小伙伴们,这篇关于《Mysql日期查询的详细介绍》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布数据库相关知识,快来关注吧!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表