简体   繁体   English

如何将来自不同子查询的多个SUM加到一个结果中?

[英]How do I add up multiple SUMs from different subqueries into one result?

How can I add up SUMs from different subqueries in MySQL? 如何在MySQL的不同子查询中添加SUM?

JOIN ( SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM product1_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)

JOIN ( SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM product2_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)

So I'd want to add those two up and have numQuotes be the total numQuotes. 所以我想将这两个加起来,并将numQuotes作为总数numQuotes。 However, it's a little more complicated than that, because the number of different tables is dynamic, so in any given circumstance there could be any number of subqueries. 但是,这要复杂得多,因为不同表的数量是动态的,因此在任何给定情况下都可以有任意数量的子查询。

What comes up with the following? 以下是什么?

select sum(numQuotes), customer_id from
(
  (SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM 
  product1_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)
UNION
  (SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes, customer_id FROM 
  product2_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id)
) group by customer_id;

Parentheses might be off so check them first. 括号可能已关闭,因此请先检查它们。

I've solved it by changing the JOINs to LEFT JOINs and using IFNULL(numQuotes".$k.",0)+ inside the PHP loop that puts the queries together, where $k is an index. 我已经通过将JOIN更改为LEFT JOIN并在将查询组合在一起的PHP循环中使用IFNULL(numQuotes".$k.",0)+来解决了该问题,其中$k是一个索引。

So the end result is something like: 所以最终结果是这样的:

SELECT IFNULL(numQuotes0,0)+IFNULL(numQuotes1,0) AS totalQuotes FROM ...

LEFT JOIN ( SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes0, customer_id FROM product1_quote GROUP BY customer_id ) p1q ON (p1q.customer_id = c.customer_id) LEFT JOIN ( SELECT SUM(IF(isPurchased='0', 1, 0)) AS numQuotes1, customer_id FROM product2_quote GROUP BY customer_id ) p2q ON (p2q.customer_id = c.customer_id)

The LEFT JOINs return NULL if no results are found, hence the need for IFNULL . 如果未找到结果,则LEFT JOINs返回NULL,因此需要IFNULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM