2014-09-05 111 views
1

有人可以告訴我如何改進下面的查詢,並使其成爲一個陳述而不是兩個陳述?由於如何改善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

回答

2

使用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