Adding 2 mysql queries that has same no of fields but from diff tables
Below is my code to add the two different query results into one. This is working fine when both the queries have same no.of rows.
eg:
row1 = 1 2 3 (Query1)
row2 = 3 5 5 (Query2)
o/p: 4 7 8
Let's say, I have few rows which are not exactly matched with first query.
eg:
row1 = 1 2 3 2 (Query1)
row2 = 3 empty empty 5 (Query2)
o/p : 4 2 3 7 (I want the o/p to be like this)
empty means there is no data from the second query.
In my while, && working fine when the 2 queri开发者_JS百科es have same no.of rows.
while (($row1 = mysql_fetch_assoc($rs1)) && ($row2 = mysql_fetch_assoc($rs2)))
{
$strHtml .= "<tr>";
$strHtml .= "<td align=center colspan=3>".($row1['Calls']+$row2['Calls'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['actual_duration(min)A']+$row2['actual_duration(min)A'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['call_usage']+$row2['call_usage'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['disconnection_charge']+$row2['disconnection_charge'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['total_revenue']+$row2['total_revenue'])."</td>";
$strHtml .= "</tr>";
}
Is the while loop i am using correct or there is any other better solution for this?
please help me, Thanks in advance.
If you don't want to do it all in the SQL query using an OUTER JOIN as @paulsm4 suggests, you might try changing your while to an ||. Then check $row1 and $row2 inside the loop to see if they are empty and calculate your sums accordingly. Is that sufficient? I can put together code if you like...
You could compute all db-side and render a simpler result:
select ifnull(a,0)+ifnull(c,0), ifnull(b,0)+ifnull(d,0) from (select a, b from table1) as x, (select c, d from table2) as y
I can think of a few different ways you can solve this, some in mysql and some in php. I don't know which one you prefer, so I'll list a couple.
mysql solution #1: Set the default value of your columns to 0, so you will never get empty results. (You'll get 0 instead, and then the addition will work fine)
mysql solution #2:
You can use IFNULL
as @Josh suggested, or COALESCE
will also work.
php solution #1: loop through your data, and assign empty values to 0.
foreach($row1 as &$value) {
if(empty($value)) { $value = 0; }
}
unset($value);
foreach($row2 as &$value) {
if(empty($value)) { $value = 0; }
}
unset($value);
精彩评论