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

时间:2010-09-02 10:46:19

标签: 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)

所以我想要添加这两个并且numQuotes是总numQuotes。但是,它有点复杂,因为不同表的数量是动态的,因此在任何给定的情况下都可以有任意数量的子查询。

2 个答案:

答案 0 :(得分:1)

以下是什么?

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;

括号可能已关闭,请先检查它们。

答案 1 :(得分:0)

我通过将JOIN更改为LEFT JOIN并在PHP循环中使用IFNULL(numQuotes".$k.",0)+将查询放在一起来解决它,其中$k是索引。

所以最终的结果是:

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)

如果没有找到结果,则LEFT JOIN返回NULL,因此需要IFNULL