[英]Postgres - query taking long time
I have a query which is taking a long time.我有一个查询需要很长时间。 Is there anyway to write it better and in optimized way:无论如何,是否可以更好地以优化的方式编写它:
select 1, my_text from (
select distinct a.my_text||'_'||b.my_text my_text from (
select r_id, my_text
from tmp_v
where r_id in (
select o_id
from tmp_recid
) and v_id in (
select v_id
from o_v
where v_id in (
select o_id from tmp_record_vaid
union
select o_id from tmp_vue_vaid
) and va_nm = 'My V'
)
) a,
(
select r_id, my_text
from tmp_v
where r_id in (
select o_id
from tmp_recid
) and v_id in (
select v_id
from o_v
where v_id in (
select o_id from tmp_record_vaid
union
select o_id from tmp_vue_vaid
) and va_nm = 'My V 2'
)
) b
where a.r_id = b.r_id
except
select e_nm
from myp_ent_id
where p_m_id = 1 and entity_id in (
select entity_id
from o_e_t
where p_m_id = 1 and tag = 'Ample' and tag_category = 'My Type'
)
) a;
First level optimization: I combined two sub queries a and b(tmp_v) into one using CASE as the conditions are common for both.第一级优化:我使用 CASE 将两个子查询 a 和 b(tmp_v) 合并为一个,因为两者的条件都相同。
select 1,my_text(
select distinct string_agg(amytext,'')||'_'||string_agg(bmytext,'') as mytext(
select r_id,case va_nm='My V' then my_text else null end as amy_text,case va_nm='My V 2' then my_text else null end as bmy_text
from tmp_v
where r_id in
(select o_id from tmp_recid)
and v_id in (select v_id from o_v where v_id in (select o_id from tmp_record_vaid union select o_id from tmp_vue_vaid))
)
except
select e_nm
from myp_ent_id
where p_m_id = 1 and entity_id in (
select entity_id
from o_e_t
where p_m_id = 1 and tag = 'Ample' and tag_category = 'My Type'
)
)a;
Further you can replace IN with EXISTS.此外,您可以用 EXISTS 替换 IN。
please, try with below query except "except query":请尝试以下查询,除了“除了查询”:
select 1, distinct(CONCAT(TV1.my_text, '_'))
from tmp_v TV1
left outer join tmp_recid TR1 on TR1.o_id = TV1.r_id
left outer join o_v OV1 on OV1.v_id = TV1.v_id and OV1.va_nm in ('My V', 'My V 2')
left outer join tmp_record_vaid TRV1 on OV1.v_id = TRV1.o_id
left outer join tmp_vue_vaid TVV1 on OV1.v_id = TVV1.o_id
where TR1.o_id is not null and (TRV1.o_id is not null OR TVV1.o_id is not null)
group by TV1.r_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.