You can‘t specify target table ‘Person‘ for update in FROM clause

There was such a problem when brushing sql questions 
Input:  
Person table: 
+----+------------------+ 
| id | email | 
+---- +------------------+ 
| 1 | [email protected] | 
| 2 | [email protected] | 
| 3 | [email protected] | 
+-- --+------------------+ Output: 
+----+------------------+ 
| id | email | 
+----+------------------+ 
| 1 | [email protected] | 
| 2 | [email protected] | 
+-- --+------------------+ Explanation: [email protected] repeated twice. We keep the smallest Id = 1.
 

Write a SQL delete statement to delete all duplicate emails and keep only one unique email with the smallest id.

Return the result table in any order . ( Note : You only need to write the delete statement, and the remaining results will be queried automatically)

DELETE

FROM

  Person

WHERE

  id NOT IN (SELECT min( id ) FROM Person  GROUP BY email )

will report an error

You can't specify target table 'Person' for update in FROM clause

When checking the update table

You can't specify target table 'table name' for update in FROM clause, which means that you cannot select some values ​​in the same table first, and then update this table (in the same statement), that is You cannot update the value of a field based on the value of a field.

Add a layer of select to the classic

DELETE

FROM

  Person

WHERE

  id NOT IN (SELECT * FROM ( SELECT min( id ) FROM Person GROUP BY email ) t)

Guess you like

Origin blog.csdn.net/qq_43433185/article/details/130794274