[MySQL Exception] Solution to the You can't specify target table for update in FROM clause error in MySQL

Solution to the error You can't specify target table for update in FROM clause in MySQL

1. Background description

MySQL database, version number is 5.7.37 (the statement is SELECT VERSION();)

There is a table in the mysql database device_data_monitor, and the requirement is to change the value of a column in this table. So use the following statement to update pillar_idthe value of this column.

UPDATE device_data_monitor 
SET pillar_id = 29 
WHERE
	monitor_id IN ( SELECT monitor_id FROM device_data_monitor WHERE pillar_id = 10 );

The result will be an error with the following content:

You can‘t specify target table for update in FROM clause The result is as follows:

Insert image description here

2. Cause analysis

In MySQL, you may encounter You can’t specify target table ‘表名’ for update in FROM clause errors like this

What it means is that in the same statement, selectcertain values ​​in the same table cannot be output first, and then updatein this table, that is, the value of a certain field cannot be updated based on the judgment of a certain field value.

The solution to this problem is mentioned on the MySQL official website: MySQL-UPDATE- Pull to the bottom of the document

You can’t specify target table ‘表名’ for update in FROM clause The reason for such an error is that MySQL does not support referencing the update target table in a subquery.

What we want to update is device_data_monitorthis table, and data is queried from this table in the FROM statement of the subquery. This is not allowed in MySQL. The reason for this provision is also to consider data security.

3. Solution

Solution: This error can be avoided selectby passing the results through an intermediate table selectone more time.

UPDATE device_data_monitor 
SET pillar_id = 29 
WHERE
	monitor_id IN ( SELECT monitor_id FROM (SELECT monitor_id FROM device_data_monitor WHERE pillar_id = 10) a );

4. The pits that have been stepped on

The result of the innermost SELECTstatement is used as a virtual table. Note: This virtual table must have an alias, otherwise another error will be reported, as shown in the following figure:

Insert image description here

The solution to this error is to add an alias to the virtual table in the subquery statement. For example, there is an alias named a in the SQL statement in the solution.

This article is finished!

Guess you like

Origin blog.csdn.net/weixin_44299027/article/details/135060478