You can't specify target table'a' for update in FROM clause-MySQL uses the same table data to update fields

You can't specify target table'a' for update in FROM clause
Have you encountered this error?

I encountered this error when I used the update statement to update the data table. My scenario is to update a field of a row of data in the same table to the same value as the corresponding field in another row of the same table.

The following is the resolution process.

1. The problem to be solved

In MySQL, you need to use the existing field of one row of data to update the field of another row of data. For example, suppose there is the following database table student_info:

student_info

id name school
1 Akari Kuang Heng Primary School
2 Xiao Hong Hogwarts School of Witchcraft and Wizardry Elementary School
3 Xiaohua Lizhuang Primary School

Now we need to change the school of Xiaoming and Xiaohong to be consistent with Xiaohua's. How should we write SQL?

2. Natural but wrong way of writing

UPDATE school_info
SET school = (
	SELECT
		school
	FROM
		school_info
	WHERE
		NAME = '小华'
)
WHERE
	NAME IN ('小明', '小红')

Writing this way will report the following error:
You can't specify target table'a' for update in FROM clause
so writing this way is not acceptable. MySQL does not support such writing.

3. Correct writing

UPDATE school_info AS s1,
 	school_info AS s2
SET s1.school = s2.school
WHERE
	s1. NAME IN ('小明', '小红')
AND s2. NAME = '小华'

In this way, you can avoid the above-mentioned error and successfully update the data.

In addition, if you like my article, you can scan the code or directly search for "Java Interview Tips" and follow my WeChat official account. I will publish original articles regularly and look forward to your arrival
Insert picture description here

Guess you like

Origin blog.csdn.net/vxzhg/article/details/103177993