MySQL/SQL: Update with correlated subquery from the updated table itself

Following the two answers I received (none of which was complete so I wrote my own), what I eventually did is as follows:

UPDATE Table AS target
INNER JOIN 
(
select category, appearances_sum
from Table T inner join (
    select category as cat, sum(appearances) as appearances_sum
    from Table
    group by cat
) as agg
where T.category  = agg.cat
group by category
) as source
ON target.category = source.category
SET target.probability = target.appearances / source.appearances_sum 

It works very quickly. I also tried with correlated subquery but it was much slower (orders of magnitude), so I’m sticking with the join.

Leave a Comment