2010-09-02 88 views
0

如何在MySQL中添加來自不同子查詢的SUM?如何將不同子查詢中的多個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。但是,它比這更復雜一點,因爲不同表格的數量是動態的,所以在任何情況下都可能有任何數量的子查詢。

回答

0

我已經解決它通過更改聯接到左聯接並在使用IFNULL(numQuotes".$k.",0)+內部的查詢放在一起的PHP循環,其中$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)

左JOIN的,如果沒有找到結果返回NULL,因此需要IFNULL

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; 

括號可能已關閉,請先檢查它們。

相關問題