如何将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
相关产品推荐
相关产品推荐

