MYSQL's simple method for removing duplicates

  • 2020-06-07 05:25:13
  • OfStack


CREATETABLE`users`(
`id`int(10)NOTNULLAUTO_INCREMENT,
`name`char(50)NOTNULL,
PRIMARYKEY(`id`)
)


deletefromuserswhereidin(selectmin(id)fromusersgroupbynamehavingcount(name)>1);

Error: 1093youcan 'tspecifytargettable...

The reason is that the mysql delete action cannot carry the query action of this table, which means that you cannot delete the users table based on the information of users table, so this statement will report an error and cannot be executed. Simply create a temporary table as a query condition. The following


deletefromuserswhereidin(select*from(selectmin(id)fromusersgroupbynamehavingcount(name)>1));

Also note that deletefromusers cannot be aliased here

Other methods.


deleteusersasafromusersasa,(selectmin(id)id,namefromusersgroupbynamehavingcount(name)>1
)asbwherea.name=b.nameanda.id<>b.id;


Create a temporary table:


createtabletmp_usersselectmin(`id`),`name`fromusersgroupbyname;
truncatetableusers;
insertintousersselect*fromtmp_users;
droptabletmp_users;


Related articles: