You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多表中获取DocumentType=1的最新DocumentId的最优SQL方案咨询

问题描述

我拥有以下三张表:

Corporate表

CorporateId    DocumentType    DocumentId     DocumentDate (dd/MM/YYYY)
  1              1              1               11/12/2022
  2              2              2               11/12/2022
  3              3              4               11/12/2022

Employee表

EmployeeId    DocumentType    DocumentId      DocumentDate (dd/MM/YYYY)
  1              1              7               15/12/2022
  2              4              3               15/12/2022
  3              5              5               15/12/2022

Car表

CarId       DocumentType    DocumentId      DocumentDate (dd/MM/YYYY)
  1              1              6               10/12/2022
  2              4              8               10/12/2022
  3              6              9               10/12/2022

我需要从上述所有表中,获取DocumentType为1的最新DocumentId(依据最晚的DocumentDate),预期结果为DocumentId=7。我知道可以通过UNION合并三张表后使用DISTINCT实现,但担心该方案性能不佳,请问是否有更优的实现方法?


优化实现方案

方案1:分表筛选候选记录再合并

不需要全表扫描后合并,而是在每个表中单独筛选DocumentType=1的最新记录,再合并这些候选结果后取最终最大值。这种方式能大幅减少处理的数据量:

SELECT DocumentId
FROM (
    -- 取Corporate表中DocumentType=1的最新记录
    SELECT DocumentId, DocumentDate
    FROM Corporate
    WHERE DocumentType = 1
    ORDER BY DocumentDate DESC
    LIMIT 1
    UNION ALL
    -- 取Employee表中DocumentType=1的最新记录
    SELECT DocumentId, DocumentDate
    FROM Employee
    WHERE DocumentType = 1
    ORDER BY DocumentDate DESC
    LIMIT 1
    UNION ALL
    -- 取Car表中DocumentType=1的最新记录
    SELECT DocumentId, DocumentDate
    FROM Car
    WHERE DocumentType = 1
    ORDER BY DocumentDate DESC
    LIMIT 1
) AS temp_results
ORDER BY DocumentDate DESC
LIMIT 1;

方案2:基于子查询定位最大日期记录

先找出每个表中DocumentType=1的最大日期,再关联获取对应的DocumentId,最后合并比较:

SELECT DocumentId
FROM (
    SELECT c.DocumentId, c.DocumentDate
    FROM Corporate c
    WHERE c.DocumentType = 1
      AND c.DocumentDate = (SELECT MAX(DocumentDate) FROM Corporate WHERE DocumentType = 1)
    UNION ALL
    SELECT e.DocumentId, e.DocumentDate
    FROM Employee e
    WHERE e.DocumentType = 1
      AND e.DocumentDate = (SELECT MAX(DocumentDate) FROM Employee WHERE DocumentType = 1)
    UNION ALL
    SELECT ca.DocumentId, ca.DocumentDate
    FROM Car ca
    WHERE ca.DocumentType = 1
      AND ca.DocumentDate = (SELECT MAX(DocumentDate) FROM Car WHERE DocumentType = 1)
) AS temp_results
ORDER BY DocumentDate DESC
LIMIT 1;

核心性能优化点

  • 给每张表创建联合索引:CREATE INDEX idx_doc_type_date ON 表名(DocumentType, DocumentDate);,这样查询时能快速定位DocumentType=1的记录并找到最大日期,避免全表扫描。
  • 用UNION ALL替代UNION:UNION会自动执行去重排序,增加额外开销,而我们只需要合并候选记录,不需要去重。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:45:40