如何使用季节表获得最终成本产品

mwngjboj  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(246)

如何用季节表得到最终成本产品?
我有这个sql模式。http://sqlfiddle.com/#!9月79日BB30/4/0
我用这个sql

SELECT *,
       COALESCE(t1.cost, t1.base_price, `ec_products`.`price`) AS final_cost
FROM `ec_products`
LEFT JOIN
  (SELECT ec_season.cost,
          ec_season.base_price,
          ec_season.product_id
   FROM ec_season
   WHERE Duration =
       (SELECT MAX(Duration)
        FROM ec_season
        WHERE `Duration` <= 4 ) ) AS t1 ON `t1`.`product_id` = `ec_products`.`id`

但是,此sql查询存在产品id 1的错误。它给出了错误的价格30.3。但必须给这个价格40.00。因为max(duration)<=4必须是2和price 40。你能帮我吗?
我也试过这个

SELECT ec_season.cost,
              ec_season.base_price,
              ec_season.product_id
       FROM ec_season
       WHERE Duration =
           (SELECT ec_season.product_id ,  MAX(ec_season.Duration) 
FROM ec_season WHERE `Duration` <= 4 GROUP BY ec_season.product_id)

但它给了我这个错误

1241-操作数应包含1列

季节表示例

vuktfyat

vuktfyat1#

您需要匹配多个列 product_id 以及 Duration 从子查询。这是一个行子查询;mysql允许元组匹配。
尝试:

SELECT ec_season.cost,
              ec_season.base_price,
              ec_season.product_id
       FROM ec_season
       WHERE (ec_season.product_id, Duration) =
             (
              SELECT ec_season.product_id, MAX(ec_season.Duration) 
              FROM ec_season 
              WHERE `Duration` <= 4 
              GROUP BY ec_season.product_id
             )
i34xakig

i34xakig2#

问题在于:

WHERE Duration = (SELECT ec_season.product_id , 
                            MAX(ec_season.Duration) 
                     FROM ec_season
                     WHERE `Duration` <= 4
                     GROUP BY ec_season.product_id
                    )

这个 = 应后跟标量子查询。标量子查询返回一列(不超过一行)。
你大概打算:

FROM ec_season s
 WHERE s.Duration = (SELECT MAX(s2.Duration) 
                     FROM ec_season s2
                     WHERE s2.Duration <= 4 AND
                           s2.product_id = s.product_id
                    )

相关问题