MySQL获取对应时间
一、查询当前时间包含年月日
SELECT CURDATE();
SELECT CURRENT_DATE();
二、查询当前时间包含年月日时分秒
SELECT NOW();
SELECT SYSDATE();
三、查询当天数据
SELECT t1.* FROM user1 t1 WHERE TO_DAYS(t1.`birthday`) = TO_DAYS(NOW()); SELECT * FROM user1 t1 WHERE t1.`birthday` BETWEEN DATE_FORMAT(NOW(), '%Y-%m-%d 00:00:00') AND NOW(); SELECT * FROM user1 t1 WHERE DATE(t1.`birthday`) = CURDATE();
四、查询昨天的数据
SELECT * FROM user1 t1 WHERE DATE(t1.`birthday`)=DATE_SUB(CURDATE(),INTERVAL 1 DAY); SELECT * FROM user1 t1 WHERE DATE(t1.`birthday`)=DATE_ADD(CURDATE(),INTERVAL -1 DAY);
五、查询当天前的数据
SELECT * FROM user1 t1 WHERE TO_DAYS(NOW()) - TO_DAYS(t1.`birthday`) >= 1;
六、查询本月的数据
SELECT * FROM user1 t1 WHERE DATE_FORMAT(t1.`birthday`,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m');
七、查询上月的数据
SELECT t1.* FROM user1 t1 WHERE PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'),DATE_FORMAT(t1.`birthday`, '%Y%m')) = 1;
八、查询上周的数据
SELECT t1.* FROM user1 t1 WHERE DATE_FORMAT(t1.`birthday`,'%Y-%m-%d') BETWEEN
DATE_SUB(CURDATE(),INTERVAL WEEKDAY(CURDATE()) + 7 DAY) AND DATE_SUB(CURDATE(),INTERVAL WEEKDAY(CURDATE()) + 1 DAY);
九、查询本年数据
SELECT * FROM user1 t1 WHERE YEAR(t1.`birthday`) = YEAR(NOW());
十、时间相减
-- 取值可以是年月日时分秒 SELECT TIMESTAMPDIFF(YEAR,'2021-02-27 23:59:59','2021-02-28 23:59:59'); SELECT TIMESTAMPDIFF(MONTH,'2021-02-27 23:59:59','2021-02-28 23:59:59'); SELECT TIMESTAMPDIFF(DAY,'2021-02-27 23:59:59','2021-02-28 23:59:59'); SELECT TIMESTAMPDIFF(HOUR,'2021-02-27 23:59:59','2021-02-28 23:59:59'); SELECT TIMESTAMPDIFF(MINUTE,'2021-02-27 23:59:59','2021-02-28 23:59:59'); SELECT TIMESTAMPDIFF(SECOND,'2021-02-27 23:59:59','2021-02-28 23:59:59');