Mysql UPDATE基于SELECT中的最低值

时间:2013-01-22 17:57:32

标签: mysql sql-update inner-join

我有以下Mysql结构:

  • jss_products
    • productID
    • price1
  • jss_extrafields_values
    • exvalID
    • productID
    • extraFieldID
  • jss_extrafields_prices
    • exvalID
    • price1

每个产品都有一些额外的领域。我对extraFieldID = 1

感兴趣

我希望使用price1的值更新jss_extrafields_prices中的所有jss_products.price1。我有以下查询,但它只更新jss_extrafields_price中每个产品的第一个条目,而不是所有条目。

我正在尝试将jss_extrafields_prices中的价格标准化,以便对于价格为20.00的商品,jss_extrafields_prices中的每个相关条目都会变为CURRENTPRICE - 20。< / p>

这有意义吗?这是我到目前为止所拥有的

UPDATE jss_extrafields_prices AS JEP
INNER JOIN (
    SELECT P.productID, P.price1 AS P1, EP.price1, EP.exvalID FROM jss_products AS P
    INNER JOIN jss_extrafields_values AS EV
    ON P.productID = EV.productID
    INNER JOIN jss_extrafields_prices AS EP
    ON EV.exvalID = EP.exvalID
    WHERE EV.extraFieldID = 1
    GROUP BY P.productID
    ORDER BY P.productID DESC, EP.price1 DESC
) AS X
ON JEP.exvalID = X.exvalID
SET JEP.price1 = JEP.price1 - X.P1

我希望内部查询返回类似于: productID = 1090 P1 = 20.8333333 price1 = 20.8333333 exvalID = 3236

知道1090的productID有3个定价选项且其基本价格为20.83333我会想要将jss_extrafields_prices中的每个匹配产品更新为当前价格减去基准价格

这有帮助吗?

1 个答案:

答案 0 :(得分:0)

删除以前类过于本地化的一些信息,这简化为带有INNER JOIN的UPDATE:

UPDATE jss_extrafields_prices 
INNER JOIN (
    SELECT P.productID, P.price1 AS baseprice, JEP.price1 AS optionprice, JEP.exvalID, (JEP.price1 - P.price1) AS adjustedprice FROM jss_products AS P
    INNER JOIN jss_extrafields_values AS JEV
    ON P.productID = JEV.productID
    INNER JOIN jss_extrafields_prices AS JEP
    ON JEV.exvalID = JEP.exvalID
    WHERE JEV.extraFieldID = 1
) AS X
ON jss_extrafields_prices.exvalID = X.exvalID
SET jss_extrafields_prices.price1 = X.adjustedprice