mysql php从2个表中减去2个字段改进查询

时间:2012-06-11 16:24:32

标签: php mysql subtraction

嗨,大家好我试图提高我的查询以获得更好的性能是否有可能以更好的方式编写此查询,感谢您的帮助

$query = " SELECT A  FROM out_org where zone_id='1'";
$query2 = " SELECT A  FROM out_dis where zone_id='1'";

$result = mysql_query($query);
$result2 = mysql_query($query2);

echo "<table border=1 style='background-color:#F0F8FF;' >";
echo "<caption><EM>my table</EM></caption>";
echo "<tr>";
echo "<th>" .OA. "</th>" ;
echo "<th>" .DA. "</th>";
echo "<th>" .total. "</th>";
echo "</tr>";

while($row = mysql_fetch_array($result)  )
{
    while( $row2 = mysql_fetch_array($result2)){
        echo "<tr>";          
        echo "<td>" .$row['A']."</td>";
        echo "<td>" .$row2['A']."</td>";
        echo "<td>" .$total = $row['A'] - $row2['A']."</td>";         
        echo "</tr>";           
    }
    echo "</table>";
}

1 个答案:

答案 0 :(得分:0)

使用连接将SQL更改为一个查询,并在查询中执行减法:

$query = "SELECT (o1.A - o2.A) as value 
          FROM out_org o1 
               LEFT JOIN out_dis o2 
               ON o1.zone_id = o2.zone_id
           WHERE o1.zone_id='1'";