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

前端 未结 6 732
灰色年华
灰色年华 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 17:05

    Maybe not a solution, but some thoughts about why it doesn't work in the first place:

    Reading data from a table and also writing data into that same table is somewhat an ill-defined task. In what order should the data be read and written? Should newly written data be considered when reading it back from the same table? MySQL refusing to execute this isn't just because of a limitation, it's because it's not a well-defined task.

    The solutions involving SELECT ... FROM (SELECT * FROM table) AS tmp just dump the entire content of a table into a temporary table, which can then be used in any further outer queries, like for example an update query. This forces the order of operations to be: Select everything first into a temporary table and then use that data (instead of the data from the original table) to do the updates.

    However if the table involved is large, then this temporary copying is going to be incredibly slow. No indexes will ever speed up SELECT * FROM table.

    I might have a slow day today... but isn't the original query identical to this one, which souldn't have any problems?

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

提交回复
热议问题