MYSQL时间函数之NOW()

it2026-04-20  3

SELECT pr.user_id as userId, count(pr.user_id) from p_reservation pr where date_format(pr.create_time,'%y%m%d') = date_format(now(),'%y%m%d') GROUP BY pr.user_id

废话不多说 直接上代码。查询某张表 当天的记录, 用数据库自带函数 now()  按今天的年月日 获取当天的数据  我这个 group by 

贴上数据库创建方式自己尝试

SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for p_reservation -- ---------------------------- DROP TABLE IF EXISTS `p_reservation`; CREATE TABLE `p_reservation`  (   `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '预约ID',   `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',   `update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '修改时间',   `user_id` bigint(20) NOT NULL COMMENT '用户ID',   `pro_id` int(11) NOT NULL COMMENT '项目ID',   `amount` decimal(15, 4) NULL DEFAULT NULL COMMENT '预约支付金额',   `reserv_status` int(1) NULL DEFAULT 0 COMMENT '预约状态(0=等待,1=成功,2=失败)',   PRIMARY KEY (`id`) USING BTREE,   INDEX `user_id`(`user_id`) USING BTREE,   INDEX `reserv_status`(`reserv_status`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 49 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '预约表' ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of p_reservation -- ---------------------------- INSERT INTO `p_reservation` VALUES (37, '2020-10-22 17:25:38', '2020-10-22 17:25:38', 51877802, 1, 30.0000, 0); INSERT INTO `p_reservation` VALUES (38, '2020-10-22 17:25:38', '2020-10-22 17:30:08', 51877802, 2, 30.0000, 1); INSERT INTO `p_reservation` VALUES (39, '2020-10-22 17:25:38', '2020-10-22 17:30:09', 51877802, 3, 30.0000, 2); INSERT INTO `p_reservation` VALUES (40, '2020-10-22 17:25:38', '2020-10-22 17:30:10', 51877802, 4, 30.0000, 1); INSERT INTO `p_reservation` VALUES (41, '2020-10-22 17:25:38', '2020-10-22 17:30:10', 51877802, 5, 30.0000, 1); INSERT INTO `p_reservation` VALUES (42, '2020-10-22 17:25:38', '2020-10-22 17:30:20', 51877802, 1, 30.0000, 1); INSERT INTO `p_reservation` VALUES (43, '2020-10-22 17:25:38', '2020-10-22 17:30:13', 51877802, 2, 30.0000, 1); INSERT INTO `p_reservation` VALUES (44, '2020-10-22 17:25:38', '2020-10-22 17:30:18', 51877802, 2, 30.0000, 1); INSERT INTO `p_reservation` VALUES (45, '2020-10-22 17:25:38', '2020-10-22 17:25:38', 257535008, 1, 30.0000, 0); INSERT INTO `p_reservation` VALUES (46, '2020-10-22 17:25:38', '2020-10-22 17:25:38', 257535008, 1, 30.0000, 0); INSERT INTO `p_reservation` VALUES (47, '2020-10-22 17:25:38', '2020-10-22 17:25:38', 257535008, 1, 30.0000, 0); INSERT INTO `p_reservation` VALUES (48, '2020-10-22 17:25:38', '2020-10-22 17:25:38', 257535008, 1, 30.0000, 0); SET FOREIGN_KEY_CHECKS = 1;

不是当天的 加个!=就行了

SELECT pr.user_id as userId, count(pr.user_id) from p_reservation pr where date_format(pr.create_time,'%y%m%d') != date_format(now(),'%y%m%d') GROUP BY pr.user_id

我这里没有显示时间,自己加个时间即可。弄完了 

最新回复(0)