Speed up plpgsql that counts doc types in a loop?

2020-04-30 03:37发布

问题:

Is there a way to speed up our plpgsql function that counts certain types of docs all in one query which is executed in a loop? ALL in one query?

validador := (select count(id_doc) from webdte.doc_tip_cifra
              where id_doc = id_documento and id_tipo_cifra = 901); 

validador2 := (select count(id_doc) from webdte.doc_tip_cifra
               where id_doc = id_documento and id_tipo_cifra = 902); 

validador3 := (select count(id_doc) from webdte.doc_tip_cifra
               where id_doc = id_documento and id_tipo_cifra = 905); 

validador4 := (select count(id_doc) from webdte.doc_tip_cifra
               where id_doc = id_documento and id_tipo_cifra = 907); 

回答1:

It should be faster to assign all four variables in one query (only one table or index scan):

SELECT INTO validador, validador2, validador3, validador4
            sum(CASE id_tipo_cifra WHEN 901 THEN 1 ELSE 0 END)
           ,sum(CASE id_tipo_cifra WHEN 902 THEN 1 ELSE 0 END)
           ,sum(CASE id_tipo_cifra WHEN 905 THEN 1 ELSE 0 END)
           ,sum(CASE id_tipo_cifra WHEN 907 THEN 1 ELSE 0 END)
FROM   webdte.doc_tip_cifra
WHERE  id_doc = id_documento;

Same result.

Normally you would have to check id_doc for NULL in addition, but since you have a WHERE condition with = on it, it cannot be NULL.