表结构如下:
CREATE TABLE `order_info` (
`id` int NOT NULL AUTO_INCREMENT,
`info` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`time` datetime NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
数据如下:
INSERT INTO `order_info` VALUES (1, '购买了手机', '2023-08-25 05:34:17');
INSERT INTO `order_info` VALUES (2, '购买了电脑', '2023-08-25 07:30:39');
INSERT INTO `order_info` VALUES (3, '购买了护手霜', '2023-08-17 22:35:07');
INSERT INTO `order_info` VALUES (4, '购买了泡面', '2023-08-23 08:35:36');
INSERT INTO `order_info` VALUES (5, '购买了纸巾', '2023-07-21 15:26:06');
INSERT INTO `order_info` VALUES (6, '购买了自热米饭', '2021-06-20 13:21:06');
INSERT INTO `order_info` VALUES (7, '购买了移动硬盘', '2023-06-11 11:22:03');
INSERT INTO `order_info` VALUES (8, '购买了狗粮', '2023-05-10 11:21:02');
INSERT INTO `order_info` VALUES (9, '购买了猫粮', '2023-04-10 09:11:02');
INSERT INTO `order_info` VALUES (10, '购买了遥控器', '2023-08-22 22:35:07');
INSERT INTO `order_info` VALUES (11, '购买了裤子', '2023-08-15 08:35:36');
INSERT INTO `order_info` VALUES (12, '购买了鞋子', '2023-08-21 08:35:36');
INSERT INTO `order_info` VALUES (13, '购买了水杯', '2023-08-26 19:39:19');
TO_DAYS()函数:返回从0000年(公元1年)至当前日期的总天数。
NOW()函数是获取具体的时分秒,例如:2023-08-25 07:30:39
CURDATE()函数是获取当天日期,例如:2012-05-15
CURTTIME()函数是获取当前时间;,例如:11:35:34
SELECT *
FROM order_info
WHERE DATE(time) = CURDATE()
SELECT *
FROM order_info
WHERE DATE_FORMAT(time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')
SELECT *
FROM order_info
WHERE DATE_FORMAT(time,'%Y') = DATE_FORMAT(CURDATE(),'%Y')
SELECT *
FROM order_info
WHERE TO_DAYS(NOW())-TO_DAYS(time)=1
SELECT *
FROM order_info
WHERE DATE_SUB(CURRENT_DATE(),INTERVAL 10 DAY) <= time
SELECT
*
FROM
order_info
WHERE YEARWEEK(DATE_FORMAT(time,'%y%m%d'),1 ) = YEARWEEK(now())
SELECT
*
FROM
order_info
WHERE YEARWEEK(DATE_FORMAT(time,'%y%m%d'),1 ) = YEARWEEK(now())-1
SELECT
*
FROM
order_info
WHERE DATE_FORMAT(time,'%y%m') = DATE_FORMAT(DATE_SUB(CURDATE(),INTERVAL 1 MONTH),'%y%m')
SELECT *
FROM order_info
WHERE DATE_SUB(CURRENT_DATE(),INTERVAL 6 MONTH) <= time
或者
SELECT *
FROM order_info
WHERE time between DATE_SUB(now(),INTERVAL 6 MONTH) AND NOW();
SELECT
*
FROM
order_info
WHERE YEAR(time) = YEAR(DATE_SUB(CURDATE(),INTERVAL 1 YEAR))
SELECT
*
FROM
order_info
WHERE YEAR(time) = '2021'
SELECT
*
FROM
order_info
WHERE MONTH(time) = '6'
以上就是我对目前MySQL常用的一些日期操作的总结归纳!