postgresql内连接复制一些记录

时间:2017-11-07 06:50:24

标签: postgresql join

我有一个大型查询开发为cte,在某些部分我必须使用内部联接来制作次要表的总数以最小化处理的记录数量,不知何故,两个子查询几乎相同,一个工作,第二个重复8次,一些总记录

我需要使用内连接或响应时间是向天空射击15倍或更多次

with 
p0 as (select distinct on (pventa) pventa, p.tipo tpva from lecturas l 
     left join puntoventa p on l.pventa=p.numero where dia between '2017-10-01' and '2017-10-31' and p.tipo in ('A','E')),

r1 as (select p.tpva, l.pventa, dia, turno  from lecturas l
       inner join p0 p on p.pventa=l.pventa  
       where dia between '2017-10-01' and '2017-10-31'),

p1 as (select pva, remision, sum(abono), count(abono) from pagosremisiones p
      inner join movsgas m on p.pva=m.pventa and p.remision=m.folio   
      inner join r1 r      on r.pventa=m.pventa and r.dia=m.dia and r.turno=m.turno group by 1,2 order by 1,2 ),

f1 as (select c.serie, c.factura, sum(abono), count(abono) from chequefactura c
      inner join movsgas m on c.serie=m.serie and c.factura=m.factura      
      inner join r1 r      on r.pventa=m.pventa and r.dia=m.dia and r.turno=m.turno  group by 1,2 order by 1,2 )

select * from p1

Nprem和ncheck用于调试

P1和f1取决于r1,p1有效(据我所知)没有重复记录(nprem对应现有寄存器),但是,ncheck会增加某些记录,最多可达实际值的8倍

我不确定p1的正确结果是否完全是随意的,并且不知道如何纠正f1中的副本

我确实可以选择直接子查询,但我对使用连接有一定的兴趣

顺便说一下,到目前为止,直接子查询比连接更有效,可能是因为它们的结构很差

我做错了什么?

您将如何优化代码?

提前致谢

1 个答案:

答案 0 :(得分:0)

需要的技巧是新的子查询r2包括[distinct on(serie,factura)],如果我省略它,则错误仍然存​​在; r2中的重复项与f1中的重复项数量不对应,所以我不知道这么多来自哪里;再次感谢你对我的问题的可怕描述道歉

with
p0 as (select distinct on (pventa) pventa, p.tipo tpva from lecturas l
     left join puntoventa p on l.pventa=p.numero where dia between '2017-10-01' and '2017-10-31' and p.tipo in ('A','E')),

r1 as (select p.tpva, l.pventa, dia, turno  from lecturas l
       inner join p0 p on p.pventa=l.pventa
       where dia between '2017-10-01' and '2017-10-31'),

r2 as (select distinct on (serie, factura)  m.serie,m.factura from movsgas m
      inner join chequefactura c on  c.serie=m.serie and c.factura=m.factura
      inner join r1 r on r.pventa=m.pventa and r.dia=m.dia and r.turno=m.turno),

p1 as (select pva, remision, sum(abono) payp from pagosremisiones p
      inner join movsgas m on p.pva=m.pventa and p.remision=m.folio
      inner join r1 r      on r.pventa=m.pventa and r.dia=m.dia and r.turno=m.turno group by 1,2 order by 1,2 ),

f1 as (select c.serie, c.factura, sum(abono) payfr2, count(*) from chequefactura c
      inner join r2 r      on r.serie=c.serie and r.factura=c.factura  group by 1,2 order by 1,2 )