在php中结合两个mysql查询

时间:2013-06-26 15:45:56

标签: php mysql

我正在创建一个仪表板,让我了解呼叫代理状态。一个代理将在日志中有多个记录。我需要从代理日志中提取最新状态。我找到的唯一方法是查询代理表以提取当前状态更改的代理,然后查询代理日志表以获取最新状态。

有没有办法合并这两个查询。这是我的疑问

$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

3 个答案:

答案 0 :(得分:0)

为什么不将2个查询加入到在第二个查询中添加WHERE lastchange LIKE '{$today}%'条件的查询?

答案 1 :(得分:0)

使用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}%');

答案 2 :(得分:0)

你和你所拥有的很亲密。这将消除在循环中执行两个查询或查询的需要。

编辑:添加示例代码以循环结果。

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