[英]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). 我需要使用两列(mixedPoints和productQuantity)的总和进行计算,其中行属于一个表(tblSubmissionProducts)上的客户,然后将该值存储在客户表(tblCustomer)上的客户记录中。
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 使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.