MySQL Update query with left join and group by

后端 未结 3 1805
别跟我提以往
别跟我提以往 2020-12-07 15:31

I am trying to create an update query and making little progress in getting the right syntax. The following query is working:

SELECT t.Index1, t.Index2, COUN         


        
相关标签:
3条回答
  • 2020-12-07 16:07

    my example

    update card_crowd  as cardCrowd
    LEFT JOIN 
    (
    select cc.id , count(1) as num
    from card_crowd cc LEFT JOIN 
    card_crowd_r ccr on cc.id = ccr.crowd_id
    group by cc.id
    ) as tt
    on cardCrowd.id = tt.id
    set cardCrowd.join_num = tt.num;
    
    0 讨论(0)
  • 2020-12-07 16:11

    Doing a left join with a subquery will generate a giant temporary table in-memory that will have no indexes.

    For updates, try avoiding joins and using correlated subqueries instead:

    UPDATE
        Table AS t
    SET
        t.SpecialEventCount = (
            SELECT COUNT(m.EventType)
            FROM MEvents m
            WHERE m.EventType in ('A','B')
              AND m.Index1 = t.Index1
              AND m.Index2 = t.Index2
        )
    WHERE
        t.SpecialEventCount IS NULL
    

    Do some profiling, but this can be significantly faster in some cases.

    0 讨论(0)
  • 2020-12-07 16:12

    I take it that (Index1, Index2) is a unique key on Table, otherwise I would expect the reference to t.SpecialEventCount to result in an error.

    Edited query to use subquery as it didn't work using GROUP BY

    UPDATE
        Table AS t
        LEFT JOIN (
            SELECT
                Index1,
                Index2,
                COUNT(EventType) AS NumEvents
            FROM
                MEvents
            WHERE
                EventType = 'A' OR EventType = 'B'
            GROUP BY
                Index1,
                Index2
        ) AS m ON
            m.Index1 = t.Index1 AND
            m.Index2 = t.Index2
    SET
        t.SpecialEventCount = m.NumEvents
    WHERE
        t.SpecialEventCount IS NULL
    
    0 讨论(0)
提交回复
热议问题