Speed up plpgsql that counts doc types in a loop?

瘦欲@ 提交于 2019-12-02 13:08:56

问题


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.



来源:https://stackoverflow.com/questions/11613257/speed-up-plpgsql-that-counts-doc-types-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!