mysql> select * from user;
+----+--------+-----+
| id | name | age |
+----+--------+-----+
| 1 | 张三 | 11 |
| 2 | 张三 | 11 |
| 3 | 李四 | 11 |
+----+--------+-----+
3 rows in set (0.00 sec)
不想看文章的朋友,直接拿去
mysql> delete from user
-> where id not in
-> (select * from
-> (select min(id) from user group by name,age)as a);
试验过程:
预期sql语句
利用group by对同一数据进行分组,利用min(id)的方法找到同一数据的最小id(当然,你想最大也可以,max(id))
select min(id) from user group by name,age;
最后利用not in找到属于重复数据的id,接着删除
mysql> delete from user
-> where id not in
-> (select min(id) from user group by name,age);
ERROR 1093 (HY000): You can't specify target table 'user' for update in FROM clause
ERROR 1093 (HY000): You can’t specify target table ‘user’ for update in FROM clause
要求不能对进行查询操作的表进行update操作,也就说我们的where条件中进行了子查询,并且子查询也是针对需要进行update操作的表的,mysql不支持这种查询修改的方式。
经过查询资料,发现可以使用临时表来保存数据以此来规避错误
mysql> delete from user
-> where id not in
-> (select * from
-> (select min(id) from user group by name,age));
ERROR 1248 (42000): Every derived table must have its own alias
ERROR 1248 (42000): Every derived table must have its own alias
要求每一个派生出来的表都必须有一个自己的别名。
参考如下:
Every derived table must have its own alias(sql语句错误解决方法) - KING - CSDN博客
https://blog.csdn.net/qq_32863631/article/details/83024322
简而言之,就是在查询表的后面添加as 别名就可以了
改变一下sql语句
(a表示的是select min(id) from user group by name,age执行后的临时表)
(select * from
-> (select min(id) from user group by name,age)as a);
所以,最后的sql语句就完成了
mysql> delete from user
-> where id not in
-> (select * from
-> (select min(id) from user group by name,age)as a);
Query OK, 0 rows affected (0.00 sec)
mysql> select * from user;
+----+--------+-----+
| id | name | age |
+----+--------+-----+
| 1 | 张三 | 11 |
| 3 | 李四 | 11 |
+----+--------+-----+
2 rows in set (0.00 sec)