Table is specified twice, both as a target for 'UPDATE' and as a separate source for data in mysql

前端 未结 6 733
灰色年华
灰色年华 2020-11-27 16:42

I have below query in mysql where I want to check if branch id and year of finance type from branch_master

6条回答
  •  时光取名叫无心
    2020-11-27 16:59

    The correct answer is in this SO post.

    The problem with here accepted answer is - as was already mentioned multiple times - creating a full copy of the whole table. This is way far from optimal and the most space complex one. The idea is to materialize the subset of data used for update only, so in your case it would be like this:

    UPDATE manager as m1
    SET m1.status = 'Y'
    WHERE m1.branch_id IN (
        SELECT * FROM(
            SELECT m2.branch_id FROM manager as m2 
            WHERE (m2.branch_id,m2.year) IN (
                SELECT DISTINCT branch_id,year 
                FROM `branch_master` 
                WHERE type = 'finance')
        ) t
    )
    

    Basically you just encapsulate your previous source for data query inside of

    SELECT * FROM (...) t
    

提交回复
热议问题