使用MySQL Update语句删除重复项

时间:2014-02-18 15:20:31

标签: mysql sql-update

如何在UPDATE语句中使用计数器。例如,我在列中有一些重复记录,如下所示:

--------------------
      Ref_Number
--------------------
108001798914
108001798914
108001798914
108001798914
108001798914
108001798914

如何删除重复,结果应为

--------------------
      Ref_Number
--------------------
108001798914
108001798915
108001798916
108001798917
108001798918
108001798919

2 个答案:

答案 0 :(得分:2)

以下内容将获取新ref_number所需的信息 - 假设与现有ref_number没有冲突:

select ref_number,
       @rn := if(@refnum = ref_number, @rn + 1, 0) as seqnum,
       @refnum = rev_number
from table t cross join
     (select @rn := 0, @refnum := -1) const
order by ref_number;

您可以使用update将其放入join,假设您有id列:

update table toupdate join
             (select @rn := 0, @refnum := -1, @prev_refnum := -1) const
     set ref_number = ref_number +
                      (case when (@prev_refnum := @refnum) is null then NULL
                            when (@refnum := ref_number) is null then NULL
                            when ref_number := @prev_refnum then @rn := @rn + 1
                            else 0
                       end)
     order by ref_number;

这是一个相当复杂的陈述,因为MySQL不容易在update语句中设置变量。使用case只是设置变量以记住以前的值。它们按顺序执行,即使它们失败了。

答案 1 :(得分:1)

试试这个。在运行这些数据之前不要忘记备份数据:

CREATE TABLE temp_table LIKE my_table;

ALTER TABLE temp_table ADD UNIQUE (Ref_Number);
ALTER TABLE temp_table CHANGE Ref_Number Ref_Number INT(10)AUTO_INCREMENT PRIMARY KEY;

INSERT INTO temp_table (all,other,fields,except,refnumber,here)
SELECT all,other,fields,except,refnumber,here FROM my_table

TRUNCATE my_table;

ALTER TABLE my_table ADD UNIQUE (Ref_Number);
ALTER TABLE my_table CHANGE Ref_Number Ref_Number INT(10)AUTO_INCREMENT PRIMARY KEY;

INSERT INTO my_table 
SELECT * FROM temp_table

DROP temp_table;

这是示例sqlfiddle