mysql - 在一个查询中查询2个表并创建两个结果的差异。

时间:2014-04-06 11:35:45

标签: php mysql sql

我目前在PHP中运行两个查询,然后取每个查询的结果来创建差异:

$sec = 3600;    
$sql = "SELECT SUM(REVENUE) as C FROM REVENUE_LOG WHERE ENTRY_DATE BETWEEN (DATE_SUB(NOW(), INTERVAL $secs second)) AND (NOW())";
$res = $this->db->query($sql)->result_array();
$rev =  $res[0]['C'];

$sql = "SELECT SUM(COST) as C FROM COST_LOG WHERE ENTRY_DATE BETWEEN (DATE_SUB(NOW(), INTERVAL $secs second)) AND (NOW())";
$res = $this->db->query($sql)->result_array();
$cost =  $res[0]['C'];
$profit = $rev - $cost;

是否可以轻松将其合并为一个查询?怎么样?

1 个答案:

答案 0 :(得分:1)

您需要单独运行每个查询,然后将它们作为派生表加入:

SELECT R,C, R-C AS difference
FROM (
     SELECT SUM(REVENUE) as R
     FROM REVENUE_LOG 
     WHERE ENTRY_DATE BETWEEN (DATE_SUB(NOW(), INTERVAL $secs second)) AND (NOW())
     ) AS revenue
JOIN (
     SELECT SUM(COST) as C 
     FROM COST_LOG 
     WHERE ENTRY_DATE BETWEEN (DATE_SUB(NOW(), INTERVAL $secs second)) AND (NOW())
     ) AS cost;