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

前端 未结 3 694
遇见更好的自我
遇见更好的自我 2020-11-29 03:35

I have a generic question that I will try to explain using an example.

Say I have a table with the fields: \"id\", \"name\", \"category\", \"appearances\" and \"rati

3条回答
  •  鱼传尺愫
    2020-11-29 04:18

    This is how it is done in mssql, I think mysql is the same or similar:

    create table T (id int, ratio float, appearances int)
    insert T values (1, null, 2)
    insert T values (1, null, 3)
    
    update T
    set ratio = cast(appearances as float)/ agg.appearancesSum
    from T join (
        select id, sum(appearances) as appearancesSum
        from T
        group by id
    ) as agg on t.id = agg.id
    

提交回复
热议问题