I'm currently running two queries in PHP, then take the result of each to create the difference:
$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;
Is it possible to combine this into one query easily? How?
You need to run each query individually then JOIN them as derived tables:
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;
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.