Interview questions: mysql delete duplicate records, retaining minimum data id

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/keep12moving/article/details/102714517

Premise Description: The database is used in mysql. 
Database table: 

Title: 
Delete name the same line, and the line is reserved for the smallest line. 
Ideas: 
1. Find a different number in addition to, other incomplete information the same number. 
Keywords: group by ...... having: grouping query, my understanding of this keyword is: Find the column between different rows of the same or a few, a few require the same separated by commas. A few lines of the value of the query if required filter condition, you need to filter by having. 
sql statement is as follows: 
the SELECT from the above mentioned id t_test20191023 Group by name 
2. delete information from the summary table in the query is not the first step to get the number of data 
delete from t_test20191023 where id not in ( select id from t_test20191023 group by name order by id)

I write to you, sql statement written by the seemingly perfect, but when running mysql, this error occurs: 

The cause of the error is: update the table at the same time this query tables, queries the table at the same time went to update the table, it can be understood as a deadlock, so the emergence of this issue.

解决方法: 
在第一步中查询最小的id时,不从主表中去查找,而是根据需要的字段从构建一个第三个表,从第三个表中去获取数据。 
select id from (select id from t_test20191023 group by name order by id) 

报错
[Err] 1248 - Every derived table must have its own alias

必须给表起个别名

select id from (select id from t_test20191023 group by name order by id) b

然后删除

这样也是可以的:delete from t_test20191023 where id not in (select minid from (select min(id) as minid from t_test20191023 group by name order by id) b)

Guess you like

Origin blog.csdn.net/keep12moving/article/details/102714517