Mysql error: 1093-You can't specify target table for update in FROM clause solution, please 3-youclause
Problems Found
Recently, when processing data in some databases, I wrote the following SQL statement:
UPDATE f_studentSET school_id = 0WHERE id > ( SELECT id FROM f_student WHERE school_id = M LIMIT 1 )AND id < ( ( SELECT id FROM f_student WHERE school_id = M LIMIT 1 ) + N)
The preceding SQL statement is used to modify the data in a certain interval, but runs in a test environment and reports the following error:
[Err] 1093 – You can't specify target table ‘f_student' for update in FROM clause
Obviously, we cannot update a table that performs the query operation, that is, subquery is performed in our where condition, in addition, the subquery is for tables that require update operations. mysql does not support this query modification method.
Solution
I checked it online. To solve this problem, we can use the "Wrap" method. The following describes the SQL statement.
UPDATE f_student SET school_id = 0 WHERE id > ( SELECT id FROM ( SELECT id FROM f_student WHERE school_id = M LIMIT 1 ) AS temp ) AND id < ( ( SELECT id FROM ( SELECT id FROM f_student WHERE school_id = M LIMIT 1 ) AS temp_1 ) + N )
OK, no problem at all. Compared with the previous SQL statement, the preceding SQL statement only bypasses the id when obtaining the id, and obtains the id through a subquery instead of directly obtaining the id.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.