MySQL:使用另一个表中的计算更新所有记录

时间:2016-11-24 10:14:59

标签: mysql

我需要使用2列(mixedPoints和productQuantity)的总和进行计算,其中行属于一个表上的客户(tblSubmissionProducts),然后将该值存储在customer表(tblCustomer)上的客户记录中

  1. 需要为每位客户(10k记录)更新。
  2. 每个客户在tblSubmissionProducts中可能有0行或更多行。
  3. 仅计算mixedPoints值的位置> 0
  4. 我为一位客户创建了一个查询,但它似乎不适用于完整的表

    SET @custID = '9';
    SELECT customerID, 
    
    (SELECT ROUND(SUM(mixedPointsTotal) / SUM(productQuantity), 2) AS 'Avg Mixed Points' 
    FROM tblSubmissionProducts 
    WHERE tblSubmissionProducts.customerID = @custID),
    
    (SELECT ROUND(SUM(mixedPointsTotal) / SUM(productQuantity), 2) AS '3mth Mixed Points' 
    FROM tblSubmissionProducts 
    WHERE tblSubmissionProducts.customerID = @custID
    AND submissionProductDate BETWEEN DATE_SUB(NOW(), INTERVAL 3 MONTH) AND NOW()),
    
    (SELECT ROUND(SUM(mixedPointsTotal) / SUM(productQuantity), 2) AS '6mth Mixed Points' 
    FROM tblSubmissionProducts 
    WHERE tblSubmissionProducts.customerID = @custID
    AND submissionProductDate BETWEEN DATE_SUB(NOW(), INTERVAL 6 MONTH) AND NOW())
    
    ;
    

    这是该查询的完整列表的第一部分: 它似乎只是锁定表太长时间,只更新一小部分记录。我最终不得不取消查询。

    对此有任何帮助将不胜感激。

    UPDATE tblCustomer, tblSubmissionProducts
    SET  tblCustomer.mixedPoints = 
    (SELECT ROUND(SUM(tblSubmissionProducts.mixedPointsTotal) / SUM(tblSubmissionProducts.productQuantity), 2) 
    FROM tblSubmissionProducts WHERE tblSubmissionProducts.customerID = tblCustomer.CustomerID
    AND tblSubmissionProducts.mixedPoints > 0);
    

    非常感谢提前。

1 个答案:

答案 0 :(得分:1)

使用MySQL update-join构造,如

UPDATE tblCustomer
JOIN (SELECT customerID,
ROUND(SUM(tblSubmissionProducts.mixedPointsTotal) / SUM(tblSubmissionProducts.productQuantity), 2) as colx
FROM tblSubmissionProducts 
JOIN tblCustomer ON tblSubmissionProducts.customerID = tblCustomer.CustomerID
WHERE tblSubmissionProducts.mixedPoints > 0 ) xxx

ON xxx.customerID = tblCustomer.CustomerID
SET  tblCustomer.mixedPoints = xxx.colx;