简体   繁体   中英

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 :

"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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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