【发布时间】:2023-07-06 20:51:01
【问题描述】:
下面的查询为我提供了每个用户每天的一条记录。如何修改它,以便它为我提供每个用户每天最早的记录?
我尝试在GROUP BY 部分的date 字段上使用MIN(),但这显然不起作用。 this answer 中提到了一个 date_trunc 函数,它似乎可以满足我的要求,但它在 MySQL 中不可用。解决此问题的最佳方法是什么?
对于下面的示例数据,查询应返回 ID 为 1、3、5 和 7 的记录。
SELECT user_id, coords, date
FROM table
WHERE draft = 0
GROUP BY user_id, DAY('date')
CREATE TABLE `table` (
`id` bigint(20) UNSIGNED NOT NULL,
`user_id` int(11) NOT NULL,
`coords` point NOT NULL,
`date` datetime NOT NULL,
`draft` tinyint(4) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `table` (`id`, `user_id`, `coords`, `date`, `draft`) VALUES
(1, 1, xxx, '2020-11-08 18:01:47', 0),
(2, 1, xxx, '2020-11-08 18:05:47', 0),
(3, 1, xxx, '2020-11-09 18:06:47', 0),
(4, 1, xxx, '2020-11-09 18:07:47', 0),
(5, 2, xxx, '2020-11-08 17:01:47', 0),
(6, 2, xxx, '2020-11-08 17:05:47', 0),
(7, 2, xxx, '2020-11-09 14:00:47', 0),
(8, 2, xxx, '2020-11-09 14:05:47', 0),
【问题讨论】:
-
你的服务器版本是多少?
标签: mysql sql date select greatest-n-per-group