[英]Mysql, how to get rid from duplicated records, joins?
Lets imagine two tables: 让我们想象两个表:
username
id, name
1 username1
2 username1
3 username2
emails
id, user, name
1 1 assdf@sdf.hu
2 2 afgdf@sdf.hu
3 3 gfg@sdf.hu
the problem is there are duplicated entries. 问题是条目重复。 I cant simply drop them, because records are connected to them, so they get lost. 我不能简单地删除它们,因为记录已连接到它们,因此它们会丢失。 (for example afgdf@sdf.hu email address). (例如,afgdf @ sdf.hu电子邮件地址)。 How to solve it? 怎么解决呢?
update emails set user=1 where user=2
,然后您只需在用户名表中删除包含id 2的行
update your username tabel. 更新您的用户名表格。 For every name that is duplicate (triplet, quat...), update the emails table and replace the user with the original user id. 对于每个重复的名称(三胞胎,quat ...),更新电子邮件表,并将用户替换为原始用户ID。
First you should update table emails
to replace user
with right values to eliminate values to be deleted. 首先,您应该更新表格emails
以将user
替换为正确的值,以消除要删除的值。
update emails set user=(select min(id)
from username
where name=
(select name from username where id=emails.user));
Now delete from username
table duplicate records. 现在,从username
名表中删除重复记录。 We keep only records with MINIMAL id
for each name
: 我们仅保留每个name
具有最小id
记录:
DELETE t1.*
FROM username t1
LEFT JOIN (select min(id) mid from username group by name) t2 ON t1.ID = t2.mid
WHERE t2.mid is null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.