SQL Update Query with Aggregate Function
This question explores the use of aggregate functions in SQL update queries. The user attempts to update a field in a table with the sum of values from another table. However, their query does not work due to syntactical issues.
Analysis
The initial query presented by the user contains two main flaws:
Solution
To resolve these issues, a subquery must be employed. The subquery will compute the sum of values from the second table, grouping by the common field. The result of this subquery will then be joined with the first table and used to update the field accordingly.
The correct query:
UPDATE t1 SET t1.field1 = t2.field2Sum FROM table1 t1 INNER JOIN (select field3, sum(field2) as field2Sum from table2 group by field3) as t2 on t2.field3 = t1.field3
In this query:
The above is the detailed content of How to Update a Table Field with the Sum from Another Table Using SQL?. For more information, please follow other related articles on the PHP Chinese website!