如何从数据库中删除重复记录

时间:2012-03-09 16:19:14

标签: mysql database

我正在使用此查询列出重复记录

SELECT DISTINCT column1 from table
group by column1 HAVING count(column1) > 1

我的特定查询

SELECT DISTINCT ReportingDetailID from reportingdetail group by ReportingDetailID  HAVING count(ReportingDetailID) > 1;

效果很好!

现在我需要删除重复的条目,最终得到漂亮干净的表

我正在查看此处的查询

DELETE FROM table_name 
USING table_name, table_name AS vtable 
WHERE 
    (table_name.id > vtable.id) 
AND (table_name.req_field=req_field)

根据查询作者“替换req_field和table_name - 应该没有任何问题”

我只是不明白如何让它在我的数据库上运行

我的表名是 reportingdetail ,列名是 reportingdetailID

+-------------------+
| ReportingDetailID |
+-------------------+
|         664602311 | 
|         664602311 | 
|         664602311 | 
|         664602311 | 
+-------------------+

删除所有重复但保留一个

谢谢

3 个答案:

答案 0 :(得分:1)

删除重复行的基本原则......

CREATE TEMPORARY TABLE tmptbl AS SELECT DISTINCT * FROM myTabs;
DELETE FROM myTabs;
INSERT INTO myTabs SELECT * FROM tmptbl;

对于上述情况,我将myTabs作为表格,Id作为Id重复的列。

请根据您的要求进行更改......

答案 1 :(得分:0)

    create temporary table records_to_delete (id int(11) unsigned primary key);

    insert into records_to_delete 
    ( 
    SELECT DISTINCT ReportingDetailID from reportingdetail 
    group by ReportingDetailID  
    HAVING count(ReportingDetailID) > 1 
    );

    delete from reportingdetail 
    where ReportingDetailID in 
    ( 
    select id from records_to_delete 
    );
抱歉,没有检查语法等,但想法应该是明确的

答案 2 :(得分:-4)

DELETE FROM table_name 
USING table_name, table_name AS vtable 
WHERE table_name.id > vtable.id
AND table_name.req_field=req_field