简体   繁体   English

在PHP中结合两个MySQL查询

[英]combining two mysql queries in php

I am creating a dashboard to keep me updated on call agent status.an agent will have multiple records in the log. 我正在创建一个仪表板以使我随时了解呼叫座席状态。一个座席将在日志中有多个记录。 I need to pull the most recent status from the agent log. 我需要从代理日志中获取最新状态。 The only way I have found is to query the agent table to pull the agents with status changes made today and then query the agent log table to pull the most recent status. 我发现的唯一方法是查询代理表以提取具有今天所做的状态更改的代理,然后查询代理日志表以获取最新状态。

is there a way to combine the two queries.? 有没有办法结合两个查询。 Here are my queries 这是我的查询

$sql_get_agents = "SELECT id FROM agent WHERE lastchange LIKE '{$today}%'";
            if($dta = mysql_query($sql_get_agents)){

                while($agent = mysql_fetch_assoc($dta)){
                $curr_agent[] = $agent;

                }

                foreach($curr_agent as $agents_online){
                    $get_status_sql = "SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
                    INNER JOIN agent a ON al.agentid = a.id
                    INNER JOIN agent_status s ON a.agent_statusid = s.id
                    WHERE al.agentid = '{$agents_online['id']}'";
                    if($dta2 = mysql_query($get_status_sql)){                               
                        while($agent_status = mysql_fetch_assoc($dta2)){
                        $curr_status[] = $agent_status;                         
                        }
                    }

                }//end for each

                return $curr_status;
            }//end if

您为什么不将2个查询合并为一个,在第二个查询中添加WHERE lastchange LIKE '{$today}%'条件?

Using the IN clause should work : 使用IN子句应该起作用:

"SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
                    INNER JOIN agent a ON al.agentid = a.id
                    INNER JOIN agent_status s ON a.agent_statusid = s.id
                    WHERE al.agentid IN (SELECT id FROM agent WHERE lastchange LIKE '{$today}%');

You were close with what you have. 您已经拥有了一切。 This will get rid of the need to do both queries, or query in a loop. 这样就无需执行两个查询或循环查询。

edit : adding example code to loop over the results as well. 编辑 :添加示例代码以遍历结果。

edit2 : changed query. edit2 :更改查询。

$query = "SELECT 
   a.firstname,
   a.lastname,
   al.agentid,
   al.agent_statusid,
   s.id as statusid,
   s.status,
   MAX(al.datetime) as datetime 
FROM agent a
   LEFT JOIN agent_log al ON al.agentid = a.id
   LEFT JOIN agent_status s ON a.agent_statusid = s.id
WHERE a.lastchange LIKE '{$today}%'";

$status = array();
$results = mysql_query( $query );
while( $agent = mysql_fetch_assoc( $results ) )
    $status[] = $agent;

print_r( $status );

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

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