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

前端 未结 3 679
遇见更好的自我
遇见更好的自我 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:04

    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.

    0 讨论(0)
  • 2020-11-29 04:11

    Use joins right after UPDATE: Reference Manual – 13.2.11 UPDATE Syntax

    so UPDATE table1 inner join table2 on .... set table1.foo=value where table2.bla = someothervalue

    With these kind of things, always look at the manual. MySql has a proper reference manual, so it shouldn't be that hard to get the right syntax ;)

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题