如何在不使用WITH子句的情况下连接PostgreSQL返回表的函数结果?
不使用WITH子句的替代写法
完全可以不用WITH子句,直接把函数返回的结果作为数据源参与JOIN操作,有两种常见写法:
写法一:直接在JOIN中引用函数
把函数调用直接当作表来使用,省去子查询的包裹:
select consultant_profiles.id, matching_data.city_matching from consultant_profiles LEFT OUTER JOIN consultants_matching_data_for_project(6001) as matching_data on matching_data.consultant_profile_id = consultant_profiles.id;
写法二:用子查询替代WITH子句
如果需要对函数返回的结果先做额外处理(比如过滤字段),可以用子查询包裹函数调用:
select consultant_profiles.id, matching_data.city_matching from consultant_profiles LEFT OUTER JOIN ( select * from consultants_matching_data_for_project(6001) ) as matching_data on matching_data.consultant_profile_id = consultant_profiles.id;
这两种写法和原WITH子句的逻辑完全一致,数据库会对它们做等价的查询优化,性能上没有差异。
内容的提问来源于stack exchange,提问作者Mateusz Urbański
相关产品推荐
相关产品推荐

