You need to enable JavaScript to run this app. SQL条件连接优化方案:减少JOIN次数 单次关联获取目标数据
优惠活动
大模型
产品
解决方案
定价
更多

SQL条件连接优化方案:减少JOIN次数 单次关联获取目标数据

解决方案

你可以通过一次关联加条件判断实现需求,无需两次JOIN,具体SQL如下:

select 
  case 
    when auth_date is not null and auth_nbr is not null and debit_date is null and debit_nbr is null then auth_date
    else debit_date 
  end as dw_date,
  case 
    when auth_date is not null and auth_nbr is not null and debit_date is null and debit_nbr is null then auth_nbr
    else debit_nbr 
  end as dw_nbr,
  t2.txn_amt as amt
from t1
join t2 
  on t1.txn_dttm = t2.txn_dttm 
  and t1.audit_num = t2.audit_num
where 
  -- 匹配第一种场景:仅auth字段非空,且iss_id相等
  (auth_date is not null and auth_nbr is not null and debit_date is null and debit_nbr is null and t1.iss_id = t2.iss_id)
  -- 匹配第二种场景:debit字段非空
  or (debit_date is not null and debit_nbr is not null)

逻辑说明

  • 关联条件取两种场景的公共部分:txn_dttm和audit_num相等,保证一次关联就能覆盖所有需要匹配的t2记录
  • 用case when根据场景判断取auth还是debit的字段作为输出的dw_date和dw_nbr
  • where条件里补充第一种场景额外要求的iss_id相等校验,避免关联出不符合规则的记录
  • 执行后得到的结果和你原来用union all两次关联的结果完全一致,关联次数从2次降到1次,能有效降低运算开销

优化提示

如果你的业务逻辑里audit_num是t1和t2的唯一匹配键(即不会出现相同audit_num对应不同txn_dttm的情况),可以把关联条件简化为仅on t1.audit_num = t2.audit_num,关联效率会更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 10:12:03