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

如何将SQL中两次关联where_to_pay表的join操作合并为一个?

完全可以通过窗口函数实现同等逻辑,且只需扫描一次where_to_pay表,省去额外的join操作,性能更优。

你现有写法的返回结果是所有wallet关联的where_to_pay记录,同时每行追加对应wallet_id下的最大business_id值。如果你的需求就是如此,可直接用max()窗口函数改写:

select w.*, wtp.*
from wallet w
join (
    select 
        *,
        max(business_id) over (partition by wallet_id) as max_business_id
    from where_to_pay
) wtp on wtp.wallet_id = w.id

如果你的实际需求是每个wallet仅保留business_id最大的那一条where_to_pay记录,原SQL无法实现该效果,此时可以用row_number()窗口函数实现:

select w.*, wtp.*
from wallet w
join (
    select 
        *,
        row_number() over (partition by wallet_id order by business_id desc) as rn
    from where_to_pay
) wtp on wtp.wallet_id = w.id and wtp.rn = 1

两种改写方式都避免了额外的分组聚合和二次join操作,数据量越大性能提升越明显。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:27:01