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) <= 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之日期查詢內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: