简体   繁体   English

如何在MySQL中查找重复的字段值并将其删除

[英]How to find duplicated field values and delete them in MySQL

Consider we have a field named (username) in our table named (tpl_users), now this table has lots of duplicated rows 考虑我们在名为(tpl_users)的表中有一个名为(username)的字段,现在这个表有很多重复的行

I wrote this code to delete duplicated usernames: 我写了这段代码来删除重复的用户名:

Delete FROM tpl_users WHERE username = username;

How is it possible to delete duplicated usernames? 如何删除重复的用户名?

Your query deletes all the rows where the user name is not NULL. 您的查询将删除用户名不为NULL的所有行。

If you want to identify the user names which are associated with more than one row: 如果要标识与多行关联的用户名:

SELECT username
  FROM tpl_users
 GROUP BY username
HAVING COUNT(*) > 1;

Before converting that into a DELETE, you need to be aware that the majority of queries will delete all the records associated with a duplicated name, rather than retaining just one of the duplicates. 在将其转换为DELETE之前,您需要知道大多数查询将删除与重复名称关联的所有记录,而不是仅保留其中一个重复项。

What you want to do is delete duplicate rows. 你想要做的是删除重复的行。

You'll do this by finding all non-duplicate rows, and replacing the table with those rows: 您将通过查找所有非重复行并将表替换为这些行来执行此操作:

create table tpl_users_new as select distinct * from tpl_users;

alter table tpl_users rename to tpl_users_old;

alter table tpl_users_new rename to tpl_users;

If you want to keep the users with the lowest id, first make sure this query has what you want to remove (and backup your database): 如果要保持用户ID最低,请首先确保此查询包含要删除的内容(并备份数据库):

SELECT u1.id, u1.username FROM tpl_users u1 LEFT JOIN tpl_users u2 ON u1.username = u2.username WHERE u1.id > u2.id;

Then, if your database is backed up, and you're sure the above statement represents what you want to remove. 然后,如果您的数据库已备份,并且您确定上述语句代表您要删除的内容。

DELETE u1 FROM tpl_users u1 LEFT JOIN tpl_users u2 ON u1.username = u2.username WHERE u1.id > u2.id

Assuming you have a primary key column in the table, you can do this: 假设表中有一个主键列,您可以这样做:

DELETE
FROM tpl_uers
USING tpl_users, tpl_users AS vtable
WHERE vtable.id > tpl_users.id
AND tpl_users.username = vtable.username

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM