简体   繁体   English

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

[英]Optimise querying the sums of values for several keys in PHP

I have a table in Postgres with SIP-log. 我在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   | 

I need to sum all sec in "in" and "out" with single SIP and group by SIP number. 我需要用单个SIP并按SIP编号对“输入”和“输出”中的所有sec求和。

Example: 例:

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

Now I use this code. 现在,我使用此代码。 But it runs in a loop and takes very long. 但是它循环运行,并且需要很长时间。

$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;
}

How can I optimise the query? 如何优化查询?

You should compose and run a query like this: 您应该编写并运行如下查询:

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+');

You'll have to replace the <...> in the above with your actual values. 您必须将上面的<...>替换为实际值。

The LIKE ANY condition will pass everything that matches one of the patterns. LIKE ANY条件将传递与模式之一匹配的所有内容。

This way you can get it all in a single query, which will be more efficient. 这样,您可以在单个查询中获得全部信息,这将更加高效。

Indexes on calldate::text and out may speed up processing. calldate::textout上的索引可以加快处理速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM