有订单表和用户表,如何获取用户的最新的一条订单记录?
订单表
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(10) NOT NULL DEFAULT 0,
`created_at` datetime(0) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB ;
INSERT INTO `orders` VALUES (1, 1, '2023-10-11 15:15:18');
INSERT INTO `orders` VALUES (2, 1, '2023-10-11 15:15:57');
INSERT INTO `orders` VALUES (3, 2, '2023-10-11 15:16:06');
INSERT INTO `orders` VALUES (4, 2, '2023-10-11 15:16:15');
INSERT INTO `orders` VALUES (5, 1, '2023-10-11 15:16:22');
INSERT INTO `orders` VALUES (6, 2, '2023-10-11 15:16:32');
用户表
CREATE TABLE `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
PRIMARY KEY (`uid`) USING BTREE
) ENGINE = InnoDB ;
INSERT INTO `users` VALUES (1, '张三');
INSERT INTO `users` VALUES (2, '李四');
如果直接使用group by 去获取数据,获取到的是最旧的一条数据。
可以搭配max函数来实现。
select * from orders where id in(select max(id) from orders GROUP BY uid);