前言
我们经常会遇到使用MySQL数据库查询某一年,某月,某日的数据,我们该如何写sql语句呢?本文给出了一种解决办法。文章源自随机的未知-https://sjdwz.com/11186.html
准备工作
表结构如下
-- ----------------------------
-- 学生入学时间表
-- ----------------------------
DROP TABLE IF EXISTS `student_table`;
CREATE TABLE `student_table` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '学号',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '名字',
`entrance_time` datetime(0) NULL DEFAULT NULL COMMENT '入学时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
插入数据
-- ----------------------------
-- 插入数据
-- ----------------------------
INSERT INTO `student_table` VALUES (1, '001', '张三', '2022-01-01 10:10:10');
INSERT INTO `student_table` VALUES (2, '002', '李四', '2021-02-02 10:10:10');
INSERT INTO `student_table` VALUES (3, '003', '张大三', '2016-02-02 10:10:10');
INSERT INTO `student_table` VALUES (4, '004', '黄蓉', '2017-10-02 10:10:10');
INSERT INTO `student_table` VALUES (5, '005', '小龙女', '2012-01-02 10:10:10');
INSERT INTO `student_table` VALUES (6, '006', '杨过', '2018-01-02 10:10:10');
INSERT INTO `student_table` VALUES (7, '007', '郭靖', '2011-10-02 10:10:10');
查询2017年入学的学生数据
select * from student_table where year(entrance_time) = '2017';
可查出如下数据:文章源自随机的未知-https://sjdwz.com/11186.html
查询1月份的数据
select * from student_table where month(entrance_time) = '01';
可查出如下数据:文章源自随机的未知-https://sjdwz.com/11186.html
查询2018年1月份的数据
select * from student_table where year(entrance_time) = '2018' and month(entrance_time) = '01';
可查出如下数据:文章源自随机的未知-https://sjdwz.com/11186.html
查询2日的数据
select * from student_table where day(entrance_time) = '02';
可查出如下数据文章源自随机的未知-https://sjdwz.com/11186.html
欢迎关注
欢迎关注微信公众号:随机的未知文章源自随机的未知-https://sjdwz.com/11186.html
欢迎关注本站微信公众号:随机的未知 如果喜欢本文,欢迎点赞,收藏,转发,打赏。