将重复的电子邮件更新为其他值

时间:2016-06-27 23:15:28

标签: mysql

我有一个用户表,其中"电子邮件"列不是UNIQUE。不幸的是,有重复电子邮件的记录。

我需要将此表导入到另一个用户表中,其中" email"列是UNIQUE

我正在考虑将任何重复的电子邮件更新为其他值,以便不再有重复项。

例如,如果我有三条记录使用相同的电子邮件" example@example.com。"然后保留其中一个并将其他两个更新为" example@example.com [随机字符串]。"

我应该运行哪些SQL语句来实现此目的?谢谢!

修改

测试戈登解决方案的表格 -

enter image description here

结果 -

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用变量:

select concat(u.email,
              (case when @e = email then concat('[', @rn := @rn + 1, ']')
                    when (@e := email) is null then '' -- never happens
                    when (@rn := 1) is null then '' -- never happens
                    else ''
               end))
from users u cross join
     (select @e := '', @rn := 0) params
order by u.email;

编辑:

嗯,上面的内容在SQL Fiddle中没有用,但是这个版本does

select concat(u.email,
              if(@e = u.email, concat('[', @rn := @rn + 1, ']'),
                 if(@e := u.email, if(@rn := 1, '', ''), '')
                )
             ), @e, @rn
from users u cross join
     (select @e := '', @rn := 0) params
order by u.email;