优化查询PHP中几个键的值总和

时间:2018-11-09 09:33:16

标签: php postgresql sqlperformance

我在Postgres中有一个带SIP日志的表。

|   in    |       out      |   sec   |
|   112   | sip/113-random |    12   | 
|   113   | sip/112-random |    45   | 
|   112   | sip/114-random |    40   | 
|   113   | sip/114-random |    35   | 
|   117   | sip/113-random |    11   | 
|   117   | sip/113-random |    25   | 
|   115   | sip/112-random |    98   | 
|   115   | sip/117-random |    78   | 
|   112   | sip/113-random |    18   | 

我需要使用单个SIP并按SIP编号对“ {in”和“ out”中的所有sec求和。

示例:

....
112 - 54
113 - 152
115 - 25
....

现在我使用此代码。但是它循环运行,并且需要很长时间。

$array_sip=array(110,111 ....  199);

foreach ($array_sip as $sip) {
    $sum_out=0;
    $sum_in=0;
    $sql = "SELECT  SUM(sec) AS sec 
            FROM public.cdr 
            WHERE calldate::text like '".$date."%'  
            AND disposition='ANSWERED'
            AND out like 'SIP/".$sip."%'
            AND sec > 15
            ";  
            foreach ($db->query($sql) as $row) {
                $sum_out=$row['sec'];
            }
    $sql = "SELECT  SUM(sec) AS sec 
            FROM public.cdr 
            WHERE calldate::text like '".$date."%'  
            AND disposition='ANSWERED'
            AND in = '".$sip."'
            AND sec > 3";   

            foreach ($db->query($sql) as $row) {
                $sum_in=$row['sec'];
            }
    $sum=round((($sum_out+$sum_in)/60),1);
    $loading_level.= $sip.' - '.$sum;
}

如何优化查询?

1 个答案:

答案 0 :(得分:0)

您应该编写并运行如下查询:

SELECT substring(out FROM '\d+'),
       SUM(sec) AS sec
FROM public.cdr
WHERE calldate::text LIKE '<your date>%'
AND disposition = 'ANSWERED'
AND out LIKE ANY ('SIP/<sip1>-%', 'SIP/<sip2>-%', ...)
AND sec > 15
GROUP BY substring(out FROM '\d+');

您必须用实际值替换上面的<...>

LIKE ANY条件将传递与其中一种模式匹配的所有内容。

这样,您可以在单个查询中获得全部信息,这将更加高效。

calldate::textout上的索引可以加快处理速度。