There is a similar question at here., but that one seems to be too old as the answer was provided back in 2009 and receives only seven supports. I believe there is a better strategy.
The table is as follows:
id weight cost
1 1.2 0
2 2.5 0
3 2.9 0
...
where the weight and cost are the weight and cost of an item. Now I want to update the cost of each id by giving a total cost N. The cost of each id is a fraction of the total cost based on its relative weight respect to the total weight.
Take a table with only three rows as above, the total weight is 1.2+2.5+2.9=6.6, therefore, the costs of ids 1, 2 and 3 are:
N*1.2/6.6
N*2.5/6.6
N*2.9/6.6
Is there a way for me to do this update using a single query? I tried something but it gives me the error message SQLSTATE[HY000]: General error: 1111 Invalid use of group function
; here is my code and I am wondering why exactly it cannot be done this way:
UPDATE `table`
SET `cost` = `cost` + :total_cost * `weight`/SUM(`weight`)
WHERE 1