从两个不相关的MySQL查询中添加总计

时间:2012-03-22 12:27:59

标签: mysql subquery

我正在努力找出正确的MySQL语法来添加两个查询的结果。查询从表中绘制调用记录,两者都生成单个数字结果,我需要将它们一起添加。我确信这可以通过子查询完成,但我似乎无法正确使用语法。

以下是查询:

SELECT SUM(costres) - SUM(costadmin)
FROM call_history, client
WHERE MONTH(start) = 3 AND YEAR(start) = 2012
  AND call_history.client_reseller_id = client.id
  AND client.charging_identifier <> 100000
  AND client.charging_identifier <> 999999;

SELECT SUM(costcl) - SUM(costadmin)
FROM call_history, client
WHERE MONTH(start) = 3 AND YEAR(start) = 2012
 AND call_history.client_reseller_id = client.id
 AND client.charging_identifier = 100000
 AND client.charging_identifier <> 999999;

正如我所说,我知道这很简单,但我似乎无法理解MySQL中的子查询语法!

提前致谢

乔治

2 个答案:

答案 0 :(得分:2)

怎么样 -

SELECT
    (SUM(IF(client.charging_identifier = 100000, costcl, 0)) - SUM(IF(client.charging_identifier = 100000, costadmin, 0))) +
    (SUM(IF(client.charging_identifier <> 100000, costres, 0)) - SUM(IF(client.charging_identifier <> 100000, costadmin, 0)))
FROM call_history, client
WHERE MONTH(start) = 3 AND YEAR(start) = 2012
AND call_history.client_reseller_id = client.id
AND client.charging_identifier <> 999999;

答案 1 :(得分:1)

MySQL在SELECT列表子查询中非常灵活,因此您可以执行以下操作,甚至不需要在主查询上使用FROM子句。

SELECT
  (SELECT SUM(costres) - SUM(costadmin)
   FROM call_history, client
   WHERE MONTH(start) = 3 AND YEAR(start) = 2012
    AND call_history.client_reseller_id = client.id
    AND client.charging_identifier <> 100000
    AND client.charging_identifier <> 999999
   ) + (
    SELECT SUM(costcl) - SUM(costadmin)
    FROM call_history, client
    WHERE MONTH(start) = 3 AND YEAR(start) = 2012
      AND call_history.client_reseller_id = client.id
      AND client.charging_identifier = 100000
      AND client.charging_identifier <> 999999
   ) AS yourSum;

我不记得MySQL是否在子查询中允许UNION。如果确实如此,那么在SUM()中使用UNION它们会更好一点:

SELECT SUM(total) as grand_total FROM
(
  SELECT SUM(costres) - SUM(costadmin) AS total
  FROM call_history, client
  WHERE MONTH(start) = 3 AND YEAR(start) = 2012
    AND call_history.client_reseller_id = client.id
    AND client.charging_identifier <> 100000
    AND client.charging_identifier <> 999999
  UNION ALL
  SELECT SUM(costcl) - SUM(costadmin) AS total
  FROM call_history, client
  WHERE MONTH(start) = 3 AND YEAR(start) = 2012
   AND call_history.client_reseller_id = client.id
   AND client.charging_identifier = 100000
   AND client.charging_identifier <> 999999
) unionsub

更新

快速测试告诉我,你可以在子查询中使用UNION ALL,至少在MySQL 5.6中。