2011-11-18 129 views
0

首先在這裏我想要做到:MySQL的SUM()子查詢(

獲取的etp_product.priceoption_price的總和。

SELECT 
    etp_product.product_id, 
    etp_product.price, 
    (SELECT MIN(price) AS FIELD_2 FROM etp_product_option_value pov WHERE pov.product_id = etp_product.product_id) AS option_price 
FROM 
    etp_product 
GROUP BY 
    etp_product.product_id, 
    etp_product.price 

我已經試過這樣:

SELECT 
    etp_product.product_id, 
    etp_product.price, 
    (SELECT MIN(price) AS FIELD_2 FROM etp_product_option_value pov WHERE pov.product_id = etp_product.product_id) AS option_price, 
SUM(etp_product.price + option_price) AS Total 
FROM 
    etp_product 
GROUP BY 
    etp_product.product_id, 
    etp_product.price 

但得到這個錯誤:

Unknown column 'option_price' in 'field list'

任何想法如何它可以做?

+0

別名能夠在自己的SELECT語句中被稱爲唯一的一次是在「按訂單」。否則,你必須重新進行計算,就像Bert Evans的答案一樣。 – Jason

回答

0
SELECT 
etp_product.product_id, 
    etp_product.price, 
    (SELECT MIN(price) AS FIELD_2 FROM etp_product_option_value pov WHERE pov.product_id = etp_product.product_id) AS option_price, 
etp_product.price + (SELECT MIN(price) AS FIELD_3 FROM etp_product_option_value pov WHERE pov.product_id = etp_product.product_id) AS Total 
FROM 
    etp_product 
GROUP BY 
    etp_product.product_id, 
    etp_product.price 
+0

感謝您的快速回答......它確實有效,但我從etp_product_option_value獲得了一些NULL結果。有時我有選擇,有時候我沒有選擇。 – capte

+0

因此,在某些情況下,etp_product_option_value與product_id沒有匹配?在這些情況下查詢是否有意義? – Bert

+0

ifnull會做的事情! ifnull(MIN(price),'0')感謝伯特! – capte

2
SELECT 
    p.product_id, 
    p.price, 
    IFNULL(MIN(pv.price), 0) as option_price, 
    (p.price + IFNULL(MIN(pv.price), 0)) as total 
FROM etp_product p 
JOIN etp_product_option_value pv ON WHERE pv.product_id = p.product_id 
GROUP BY 
    p.product_id, 
    p.price 
+0

JOIN幾乎總是比SELECT中的子查詢更好! – TehShrike