简体   繁体   中英

MySQL: Updating all records using calculations from another table

I need to make a calculation using the sum of 2 columns (mixedPoints and productQuantity) where the rows belongs to a customer on one table (tblSubmissionProducts), and then store that value on the customer record on the customer table (tblCustomer).

  1. This needs to be updated for every customer (10k records).
  2. Each customer may have 0 or more rows in the tblSubmissionProducts.
  3. Only calculate where the mixedPoints value > 0.

I created a query for one customer but it doesn't seem to work for the full table

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())

;

This is the first part of that query for the full list: It seems to just lock the tables for too long and only updates a fraction of the records. I end up having to cancel the query.

Any assistance with this would be appreciated.

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);

Many thanks in advance.

Use MySQL update-join construct like

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM