如何避免多次调用函数

时间:2015-07-16 07:36:11

标签: sql postgresql

SELECT c.c_epasts,DATE_PART('day', now() - (
  SELECT _get_1_darba_iestasanas.pirma_iestasanas
  FROM _get_1_darba_iestasanas(c.c_id) _get_1_darba_iestasanas(did integer, pirma_iestasanas date)
  LIMIT 1
)) AS worked_days
FROM cilveks c 
WHERE worked_days = ANY ('{182,273,365}'::int[]) AND (SELECT count(*) FROM sertifikati_lietotaji s WHERE s.id_cilveks=c.c_id)=0

我不想在SELECT和WHERE语句(两者)中创建此函数。因为它增加了查询执行时间。

我怎样才能使这个函数只执行一次,我可以在where子句中选择值和那个值?

DATE_PART('day', now() - (
  SELECT _get_1_darba_iestasanas.pirma_iestasanas
  FROM _get_1_darba_iestasanas(c.c_id) _get_1_darba_iestasanas(did integer, pirma_iestasanas date)
LIMIT 1))

1 个答案:

答案 0 :(得分:2)

将其包装在派生表中:

select * 
from (
  SELECT c.c_epasts,
            DATE_PART('day', now() - (
               SELECT _get_1_darba_iestasanas.pirma_iestasanas
               FROM _get_1_darba_iestasanas(c.c_id) _get_1_darba_iestasanas(did integer, pirma_iestasanas date)
               LIMIT 1)) AS worked_days
  FROM cilveks c 
  WHERE (SELECT count(*) FROM sertifikati_lietotaji s WHERE s.id_cilveks=c.c_id)=0
) t
where worked_days = ANY ('{182,273,365}'::int[])