- 您可以拨打一次
translate()
,而不是拨打两次replace()
.您还可以合并您的translate()
个呼叫,而不是将它们嵌套.
- 可以直接包装
regexp_split_to_table()
,而不是包装unnest(string_to_array())
.
- 作为@JNevill pointed out,您需要做的就是将您拥有的查询嵌套在CTE或子查询中,然后加入其中.
Demo at db<>fiddle:
with your_big_union as (
select field1,field2,string_agg(distinct fld,',') field3
from(
select *
from(
select field1,field2,fld
from table1 t1
left join (
select * from table2
cross join regexp_split_to_table(trim(translate(field4,'{}','')),',') fld
)t2
on concat(t1.field2,';') similar to concat('%',t2.field3,'[();]%')
)x
)b
where field2 like '%fn@_%' escape '@' and fld is not null
group by field1,field2
union
(with cte as (
select field1,field2
,''''
||translate( btrim(field2)
,E'\n"'''
,'' )
||'''' as edited_field2
from table1)
,cte2 as (
select *,t.spotted_table as spotted_target,s.spotted_table as spotted_source
from cte
left join regexp_matches(
edited_field2
,'(?:UPDATE|INTO)(?:\s+ONLY)?\s+([[:alpha:]_]+[\.\w]*|"[^"]+"(?:\."[^"]+")?)'
,'gi'
) with ordinality as target_matches(hits,n1) on true
left join unnest(target_matches.hits) with ordinality as t(spotted_table,n2) on true
left join regexp_matches(
edited_field2
,'(?:FROM|JOIN|USING|TABLE)(?:\s+ONLY)?\s+([[:alpha:]_]+[\.\w]*|"[^"]+"(?:\."[^"]+")?)'
,'gi'
) with ordinality as source_matches(hits,n1) on true
left join unnest(source_matches.hits) with ordinality as s(spotted_table,n2) on true)
select field1
,string_agg(distinct spotted_target,',') as spotted_targets
-- ,string_agg(distinct spotted_source,',') as spotted_sources
,edited_field2
from cte2 where edited_field2 not like '%fn@_%' escape '@' and spotted_target is not null
and coalesce(split_part(spotted_target,'.',1) !~* '_inc"?$',true)
and coalesce(split_part(spotted_source,'.',1) !~* '_inc"?$',true)
group by field1,edited_field2
order by field1))
select *
from table5 left join your_big_union
on lower(your_big_union.field1) = table5.field6;
- 如果
table5.field6
加入field1
,您将不会得到匹配项,因为您将'J'
升级为field
,而field6
则保留了一个预设.我不知道如果您的连接两侧只有一个'j'
,为什么您会期望3个结果.