如何改善postgresql查询?

问题描述:

有人可以告诉我如何改进下面的查询,并使其成为一个陈述而不是两个陈述?由于如何改善postgresql查询?

CREATE LOCAL TEMP TABLE tmpdetail2 
WITH (OIDS) 
ON COMMIT DROP as 
    select d2.detailid, d2.objid, d2.p 
    from _detail d2       
    where d2.detailid in (19, 106); 

    select distinct d.detailid, d.p, d.pval, d.objid 
    from _detail d 
    left join tmpdetail2 d2 
    on d.objid = d2.objid 
    where d2.objid is null 
    and d.p not in(select p from tmpdetail2) 
    order by p asc, d.detailid asc; 
+2

什么地方错了 - 你是什么,你寻求改善?它应该做什么? (样本数据?解释?)。为什么用'oids'创建临时表? PostgreSQL版本? – 2014-09-05 13:29:54

使用common table expression

with tmpdetail2 as (
    select d2.detailid, d2.objid, d2.p 
    from _detail d2       
    where d2.detailid in (19, 106) 
) 
select distinct d.detailid, d.p, d.pval, d.objid 
from _detail d 
left join tmpdetail2 d2 
    on d.objid = d2.objid 
where d2.objid is null 
    and d.p not in(select p from tmpdetail2) 
order by p asc, d.detailid asc; 
+0

感谢@a_horse,我删除了第一个分号,它工作正常。 – fs2050 2014-09-05 14:51:44

+0

@ fs2050:谢谢,那是一个复制和粘贴错误。固定。 – 2014-09-05 15:12:59