带有MIN()的MySQL SUM()子查询

时间:2011-11-18 15:16:10

标签: mysql sum min

首先,我要完成的是:

获取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

但是得到这个错误:

  

未知栏' option_price'在'字段列表'

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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