mysql - 按时间戳选择最近的不同对
问题描述
我有一个带有列的表:
- id(自增)
- created_at
- topic_id
- code_id
- 价值
该表有许多具有相同(topic_id,code_id)的行。
对于给定的主题 ID 和代码 ID 列表,我想选择具有唯一 (topic_id, code_id) 组合的最新行(= 最大 created_at)。
我试过了:
select distinct topic_id, code_id from topic_values where topic_id in (...) and code_id in (...) order by created_at desc;
这是错误的,因为:
- 它只选择 topic_id 和 code_id
- 全局按latest created_at排序(按latest created_at排序应在(topic_id,code_id)范围内。
然后我尝试了:
select * from topic_values where topic_id in (...) and code_id in (...) group by topic_id, code_id order by created_at desc;
这是错误的,因为:
- 全局按latest created_at排序(按latest created_at排序应在(topic_id,code_id)范围内。
我怎么能做到这一点?理想情况下,我希望查询利用我在表上的以下索引:
KEY `created_at` (`created_at`,`topic_id`,`code_id),
KEY `created_at_2` (`created_at`,`code_id`,`topic_id`),
KEY `topic_id` (`topic_id`,`code_id`,`created_at`),
KEY `topic_id_2` (`topic_id`,`created_at`,`code_id`),
KEY `code_id` (`code_id`,`topic_id`,`created_at`),
KEY `code_id_2` (`code_id`,`created_at`,`topic_id`),
解决方案
使用窗口函数按日期降序查找每个组顺序的第一行
select *
from (
select *, row_number() over(partition by topic_id, code_id order by created_at desc) rn
from topic_values
where topic_id in (1,2,3) and code_id in (4,5,6)
) r where rn = 1
order by id
或每个组的最大日期的子查询
select a.*
from topic_values a
join (
select topic_id, code_id, max(created_at) max_date
from topic_values
where topic_id in (1,2,3) and code_id in (4,5,6)
group by topic_id, code_id
) r on a.topic_id = r.topic_id and a.code_id = r.code_id and a.created_at = r.max_date
where
a.topic_id in (1,2,3) and a.code_id in (4,5,6)
order by id
第二个选项将获得多行,如果它发生多行具有相同的 max created_at 相同的 topic_id 和 code_id。如果需要,它可以row_number()
在第一个选项中替换为rank()
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=d4d26dffc115c9610c6e21a55d149676
推荐阅读
- azure - Azure - 具有无服务器应用程序的网络安全组
- python - 使用 Anaconda 安装 Scran 包时出错
- oracle-apex - 设置会话状态 - APEX 21.1
- regex - 从表中提取所有出现的字符串
- javascript - 加载 Vue.js 表需要很长时间(加载两次)
- r - ubuntu上离线安装R catboost包
- yii2 - 使用 Codeceoption 运行验收测试时出错
- javascript - 根据匹配字段组合两个不同的对象数组
- css - 需要触摸和无效表单的角度反应形式的 css 样式
- android - 在 Play 商店控制台上出现“android.app.RemoteServiceException”崩溃