将查询优化为一个

时间:2013-09-12 11:10:56

标签: php mysql

任何人都可以帮我减少这段代码。

$dat=  mysql_query
("SELECT wid,count(*) as count 
  FROM uptime 
  WHERE time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) 
  AND  status<>200 GROUP BY wid ORDER BY  time_stamp ASC"
);

while($ans= mysql_fetch_assoc($dat))
{
   $count_array[]=$ans;
}

foreach ($count_array as $value) 
{
   if($value['count']==2)
   {
      $id=$value['wid'];
      $add=  mysql_query("SELECT email FROM website WHERE webid='".$id."'");
      $result=  mysql_fetch_assoc($add);
      <--etc etc to send email-->
    }
}

我需要减少代码请帮助我。如果两个查询可以合并而不失去意义也对我有帮助。

3 个答案:

答案 0 :(得分:1)

这是两个表之间的简单连接:

select
    upity.wid,
    webit.email,
    count(*) as count
from
    uptime upity
        join website webby
            on upity.wid=webby.webid
where
    upity.time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) 
    and upity.status<>200
group by
    upity.wid,
    webit.email
having count=2

我写了一个really in-depth Q&A on joining tables in SQL,它将更详细地解释这一切是如何运作的。事实上,我正是出于这个原因编写的 - 能够帮助快速查询,然后能够链接到正在发生的事情的详细解释。

编辑:根据以下Zerkms与我之间的评论,如果您使用此代码,请查看执行时间。大型表在加入时可能会导致非常大的数据集,并且运行多个查询的确可能更有效。

答案 1 :(得分:0)

$dat=  mysql_query("SELECT wid,count(*) as count 
FROM uptime WHERE time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) AND  status<>200 GROUP BY wid ORDER BY  time_stamp ASC");
while($ans= mysql_fetch_assoc($dat)){
if($ans['count']==2){
  $id=$value['wid'];
 $add=  mysql_query("SELECT email FROM website WHERE webid='".$id."'");
$result=  mysql_fetch_assoc($add);
<--etc etc to send email-->
}
}

答案 2 :(得分:0)

试试这个:

$dat = mysql_query("
SELECT 
    ut.wid,ut.count(*) as count,ws.email 
FROM 
     uptime as ut 
INNER JOIN
     website as ws 
ON  
     ut.id=ws.webid  
WHERE 
     ut.time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) AND  ut.status<>200 AND ut.count=2 
GROUP BY  
      ut.wid  
ORDER BY  
       ut.time_stamp ASC");