数据库 
首页 > 数据库 > 浏览文章

Mysql日期查询的详细介绍

(编辑:jimmy 日期: 2024/11/16 浏览:3 次 )

查询当前日期

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) <= DATE(`字段`);

查询最近三十天的数据

SELECT * FROM table WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= DATE(`字段`);

查询本周的数据

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预编译
下一篇:MySQL创建用户和权限管理的方法
一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 站点导航 SiteMap