You need to enable JavaScript to run this app. MySQL多表关联查询中如何对指定4列去重获取最新变更记录
优惠活动
大模型
产品
解决方案
定价
更多

MySQL多表关联查询中如何对指定4列去重获取最新变更记录

重复结果的核心成因

原查询输出重复条目的原因很直接:

  • full_records和changelog是一对多关联关系,同一个full_records实体可对应多条变更日志
  • 如果直接在原查询前加DISTINCT,由于select输出的full_records.id、changelog.changed_on未被纳入去重规则,即便业务字段组合重复,只要这两个字段值不同,就会被判定为非重复条目,根本达不到预期去重效果
可行调整方案

方案1:窗口函数分组取最新值(优先推荐,兼容MySQL8.0+、PostgreSQL、SQL Server等绝大多数现代数据库)

该方案完全匹配需求:按full_records.domain_id、subdomain_name、type_name、content四个字段做分区,每个分区内按变更时间倒序排序,只取排第一位的记录(即每个字段组合下最新的一条变更),可精准移除指定的重复行。

select
  id,
  domain_id,
  subdomain_name,
  type_name,
  content,
  changed_on
from (
  select
    full_records.id,
    full_records.domain_id,
    subdomains.name as subdomain_name,
    types.name as type_name,
    changelog.content as content,
    changelog.changed_on,
    -- 按要求的去重字段分区,组内按变更时间倒序生成行号
    row_number() over (
      partition by full_records.domain_id, subdomains.name, types.name, changelog.content
      order by changelog.changed_on desc
    ) as rn
  from full_records
    inner join subdomains on full_records.subdomain_id = subdomains.id
    inner join types on full_records.type_id = types.id
    inner join changelog on full_records.id = changelog.full_record_id
  where
    full_records.domain_id = 2
) t
where rn = 1
order by changed_on desc

方案2:分组聚合关联(兼容MySQL5.x等不支持窗口函数的老旧数据库版本)

该方案先定位每个目标去重字段组合对应的最新变更时间,再通过关联匹配完整字段值,避免随机取非最新记录的问题。

select
  full_records.id,
  full_records.domain_id,
  subdomains.name as subdomain_name,
  types.name as type_name,
  changelog.content as content,
  changelog.changed_on
from full_records
  inner join subdomains on full_records.subdomain_id = subdomains.id
  inner join types on full_records.type_id = types.id
  inner join changelog on full_records.id = changelog.full_record_id
inner join (
  -- 按四个去重字段分组,拿到每个组合对应的最新变更时间
  select
    full_records.domain_id,
    subdomains.name as subdomain_name,
    types.name as type_name,
    changelog.content as content,
    max(changelog.changed_on) as latest_changed_on
  from full_records
    inner join subdomains on full_records.subdomain_id = subdomains.id
    inner join types on full_records.type_id = types.id
    inner join changelog on full_records.id = changelog.full_record_id
  where
    full_records.domain_id = 2
  group by full_records.domain_id, subdomains.name, types.name, changelog.content
) latest
  on full_records.domain_id = latest.domain_id
  and subdomains.name = latest.subdomain_name
  and types.name = latest.type_name
  and changelog.content = latest.content
  and changelog.changed_on = latest.latest_changed_on
where
  full_records.domain_id = 2
order by changelog.changed_on desc

注意点:如果存在不同full_records但四个业务字段完全一致的极端场景,两种方案都会保留对应组合下最新的变更记录,完全匹配“获取对应域名最新变更记录”的核心需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.02 06:45:08