mysql获取每天最早的记录

pxyaymoc  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(329)

下面的查询为每个用户每天提供1条记录。我该如何修改它,以便它为每个用户提供每天最早的记录?
我试过用 MIN()date 中的字段 GROUP BY 但这显然行不通。有一个 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),
de90aj5v

de90aj5v1#

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

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
)

第二个查询应该能够利用 (draft, user_id, date) .
或者,如果运行的是musql 8.0,也可以使用窗口函数:

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
ybzsozfc

ybzsozfc2#

选择用户id、坐标、日期 table 其中draft=0 group by day('date'),user\u id order by user\u id,date

相关问题