You need to enable JavaScript to run this app. SQL如何按条件查询distinct relation_id下最新created_at的全字段数据
优惠活动
大模型
产品
解决方案
定价
更多

SQL如何按条件查询distinct relation_id下最新created_at的全字段数据

按relation_id取最新全字段记录的实现SQL

前置说明:以下SQL中的your_table请替换为你实际使用的表名

方案1:全数据库兼容写法(支持MySQL 5.x、SQL Server、PostgreSQL等所有主流数据库)

核心逻辑:先按relation_id分组查询出每组的最大created_at值,再关联原表匹配符合条件的行:

SELECT t.*
FROM your_table t
INNER JOIN (
    SELECT relation_id, MAX(created_at) AS latest_created_time
    FROM your_table
    GROUP BY relation_id
) latest_record
ON t.relation_id = latest_record.relation_id
AND t.created_at = latest_record.latest_created_time;

边界提示:如果同一relation_id下存在多条记录的created_at完全等于最新时间,该写法会返回所有匹配行。如果需要每组仅保留1条记录,可在子查询中追加最大id的匹配条件做兜底:

SELECT t.*
FROM your_table t
INNER JOIN (
    SELECT relation_id, MAX(created_at) AS latest_created_time, MAX(id) AS latest_id
    FROM your_table
    GROUP BY relation_id
) latest_record
ON t.relation_id = latest_record.relation_id
AND t.created_at = latest_record.latest_created_time
AND t.id = latest_record.latest_id;

方案2:窗口函数精简写法(支持MySQL 8.0+、SQL Server 2012+、PostgreSQL等现代数据库)

通过ROW_NUMBER()窗口函数给每个relation_id分组内的行按created_at倒序排名,仅取排名为1的行即可。该写法不需要多表关联,大数据量下查询效率更高,且天然保证每个分组仅返回1条记录,不会出现重复冗余:

SELECT id, relation_id, someData, created_at
FROM (
    SELECT *,
        ROW_NUMBER() OVER (
            -- 按relation_id拆分独立分组
            PARTITION BY relation_id
            -- 组内按创建时间倒序,时间相同时按id倒序兜底排序
            ORDER BY created_at DESC, id DESC
        ) AS row_rank
    FROM your_table
) ranked_result
WHERE row_rank = 1;

示例数据匹配输出

针对给出的原始测试数据集,上述SQL执行后返回结果与预期完全一致:

idrelation_idsomeDatacreated_at
1123I am data2020-01-01
3321I am also data2015-01-01
4555Data2020-06-05

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.26 11:15:08