有时候,我们会在平时的工作中碰到如下的问题:
在一个数据表开始的时候,由于考虑的不完全,可能主键配置没有做好,可能在表中出现如下的重复数据
+------+-------+------+
| id | name | age |
+------+-------+------+
| 1 | jason | 23 |
| 2 | jason | 23 |
| 3 | jason | 23 |
| 4 | alex | 24 |
| 5 | alex | 24 |
+------+-------+------+
现在当我们希望去掉重复的姓名数据得到如下的结果
+------+-------+------+
| id | name | age |
+------+-------+------+
| 3 | jason | 23 |
| 5 | alex | 24 |
+------+-------+------+
开始写出了如下的一句SQL DELETE FROM TB_NAME WHERE id NOT IN (SELECT MAX(id) FROM TB_NAME GROUP BY name);
但是执行之后我们会发现如下错误:ERROR 1093 (HY000): You can't specify target table 'demo1' for update in FROM clause
后来换了一种写法,可以解决这个问题
DELETE FROM TB_NAME WHERE id NOT IN (SELECT id FROM (SELECT MAX(id) AS ID FROM TB_NAME GROUP BY name) AS TMP);