从显示的表和date_format中选择min元素的最有效查询[重复]

问题描述 投票:0回答:2

我有一个具有一百万行的表,我想获取带有最小日期并按天格式化的行。

我的桌子是:

Id  Created_at          Value
1   2019-04-08 10:35:32 254
1   2019-04-08 10:31:23 241
1   2019-04-08 11:47:32 258
2   2019-04-08 10:32:42 276
2   2019-04-08 10:34:23 280
2   2019-04-08 11:34:23 290

而且我想获取(每个小时的最小created_at值并按小时格式化):

Id  Created_at          Value
1   2019-04-08 10:00:00 241
1   2019-04-08 11:00:00 258
2   2019-04-08 10:00:00 276
2   2019-04-08 11:00:00 290

我有mysql 5.7,所以我无法建立窗口式查询。我正在研究选择此元素的最有效方法。

mysql join greatest-n-per-group min date-format
2个回答
1
投票

我会做类似的事情:

select
  t.id, m.h, t.value
from my_table t
join (
  select
    id,
    from_unixtime(floor(unix_timestamp(created_at) / 3600) * 3600) as h,
    min(created_at) as min_created_at
  from my_table
  group by id, from_unixtime(floor(unix_timestamp(created_at) / 3600) * 3600)
) m on m.id = t.id and m.min_created_at = t.created_at

1
投票

在mysql 5.7中

您可以在子查询上使用联接以获得最小结果

select  m.id, date(m.created_at) , m.value
INNER JOIN (
select  min(created_at) min_date
from  my_tbale  
group by date(created_at),hour(created_at)

) t on t.min_date  = m.created_at

确保您在my_table列(created_at,id,值)上有一个复合索引

© www.soinside.com 2019 - 2024. All rights reserved.