MySQL获得每天最早的记录

MySQL获得每天最早的记录,mysql,sql,date,select,greatest-n-per-group,Mysql,Sql,Date,Select,Greatest N Per Group,下面的查询为每个用户每天提供一条记录。如何修改它,以便为每个用户提供每天最早的记录 我尝试在groupby部分的date字段中使用MIN(),但显然不起作用。其中提到了一个date\u trunc函数,它似乎可以满足我的需求,但在MySQL中不可用。最好的办法是什么 对于下面的示例数据,查询应该返回ID为1、3、5和7的记录 SELECT user_id, coords, date FROM table WHERE draft = 0 GROUP BY user_id, DAY('date')

下面的查询为每个用户每天提供一条记录。如何修改它,以便为每个用户提供每天最早的记录

我尝试在
groupby
部分的
date
字段中使用
MIN()
,但显然不起作用。其中提到了一个
date\u 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),

典型的方法是使用相关子查询进行筛选:

select t.*
from mytable t
where t.draft = 0 and t.date = (
    select min(t1.date) 
    from mytable t1 
    where t1.draft = t.draft and t1.user_id = t.user_id and date(t1.date) = date(t.date)  
)
您可以使用半个打开的间隔进行筛选,从而稍微优化子查询:

select t.*
from mytable t
where t.draft = 0 and t.date = (
    select min(t1.date) 
    from mytable t1 
    where 
        t1.user_id = t.user_id 
        and t1.draft = t.draft
        and t1.date >= date(t.date)
        and t1.date <  date(t.date) + interval 1 day
)
使用:


你的服务器版本是什么?
select *
from (
    select t.*, row_number() over(partition by user_id, date(date) order by date) rn
    from mytable t
    where draft = 0
) t
where rn = 1
SELECT user_id, coords, date
FROM `table`
WHERE draft = 0
GROUP BY DAY('date'), user_id order by user_id, date