Mysql
 sql >> Database >  >> RDS >> Mysql

Come posso fare eco a una tabella con i risultati combinati di due query simili da due database diversi?

Modifica :

Supponendo che i tuoi risultati siano così :

Scrivi

number company    db1 Count
1      SuperCorp  5
2      SuperCorp  10

Segnala

number company    db2 Count
2      SuperCorp  10
3      SuperCorp  20

Se vuoi visualizzare una tabella come questa

number company    db1 Count db2 Count
1      SuperCorp  5         0
2      SuperCorp  10        10
3      SuperCorp  0         20

È necessario unire i risultati delle due query prima di stamparli sullo schermo. Questo è possibile grazie alla tua colonna 'numero' che può essere utilizzata come chiave del tuo array PHP.

Devi anche modificare le tue query SQL per includere una colonna falsa che rappresenta l'altro conteggio del database :

$sql1 = "SELECT num.number AS Number, com.name As company, count(*)   As \"db1 count\", 0   As \"db2 count\" 
                FROM db1.db.job_processing AS jp
                LEFT JOIN db1.db.number AS num ON num.id=jp.number_id 
                LEFT JOIN db1.db.company AS com on com.id=num.company_id 
                WHERE jp.show=1 AND jp.processing_complete=1 
                AND jp.call_start_time BETWEEN '2016-12-17' AND '2017-01-03'
                GROUP BY Number
                ORDER BY Number
                LIMIT 20";

$sql2 = "SELECT num.number AS Number, com.name AS company, COUNT(*) AS \"db2 Count\", 0   As \"db1 count\" 
            FROM db2.db.job_processing AS jp
            LEFT JOIN db2.db.number AS num ON num.id=jp.number_id 
            LEFT JOIN db2.db.company AS com on com.id=num.company_id 
            WHERE jp.show=1 AND jp.processing_complete=1 
            AND jp.call_start_time BETWEEN '2016-12-17' AND '2017-01-03'
            GROUP BY Number
            LIMIT 20";

E poi combina i 2 risultati prima per visualizzarli, in questo modo:

$results = array();
while($row = $result1->fetch_assoc()) {
     //Adding all the 1st query results 
     $results[$row['number']] = $row;
}

while($row = $result2->fetch_assoc()) {
     if(! isset($results[$row['number']]) {
          //Mean's this row is not present in the 1st database, so add it
          $results[$row['number']] = $row;
     }else {
          //Just merging the db2 Count from the 2nd database since other fields are the same
          $results[$row['number']]['db2 Count'] = $row['db2 Count'];
     }         
}


if ($results) {
      echo"<TABLE><caption>Total Call Count Overview</caption><TR>
      <TH>Number</TH>
      <TH>Company</TH>
      <TH>db1 Count</TH>
      <TH>db2 Count</TH></TR>";

    foreach($results as $row) {
         echo"<TR><TD>". $row["number"]. "</TD>";
         echo"<TD>". $row["company"]. "</TD>";
         echo"<TD>". $row["db1 Count"]. "</TD>";
         echo"<TD>". $row["db2 Count"]. "</TD></TR>";
    }
    echo"</TABLE>";
} else {
     echo"0 Results";
}