我有一个很长的 CTE 查询,为了便于阅读,我在这里缩短了它。但它尝试将州、县、市、邮政编码和街道插入到自己的表中,然后插入他们的 ID,以便在属性表中插入地址。
with tmpstate as (
insert
into
state ....on
conflict ( lower(state_code) ) do
update
set
state_code = excluded.state_code returning id,
state_code ),
tmpcounty as (
insert
into
..... on
conflict ( lower(county),
state_id ) do
update
set
county = excluded.county returning id,
county ),
tmpcity as (
insert
into
.....
values ( 'Sarasota',
(
select
id
from
tmpcounty
limit 1 ),
(
select
id
from
tmpstate
limit 1 ) ) on
conflict ( lower(city),
county_id,
state_id ) do
update
set
city = excluded.city returning id,
city ),
tmpzipcode as (
...... returning id,
zipcode ),
tmpstreet as (
.... ),
tmpproperty as(
insert
into
property (full_address,
street_address,
street_id,
city_id,
state_id,
zipcode_id,
county_id,
property_details )
values('ssss',
'ssss',
(
select
id
from
tmpstreet
limit 1),
(
select
id
from
tmpcity
limit 1),
(
select
id
from
tmpstate
limit 1),
(
select
id
from
tmpzipcode
limit 1),
(
select
id
from
tmpcounty
limit 1),
'{}') returning id)
select
id
from
property
limit 1
如果我创建插入街道、城市等的函数/触发器并返回它们的 id(如果它们存在)而不是这个长 CTE 查询,会不会有任何性能提升?
用它的 CTE 运行一个大语句将比运行几个小的语句更有效。
为单个插入使用 PL/pgSQL 函数的唯一优点是语句计划在数据库会话期间被缓存。但是如果你想利用它,你可以把你的大语句放入这样的函数中。