How to delete duplicate rows with SQL?

后端 未结 3 842
无人共我
无人共我 2020-11-27 05:30

I have a table with some rows in. Every row has a date-field. Right now, it may be duplicates of a date. I need to delete all the duplicates and only store the row with the

相关标签:
3条回答
  • 2020-11-27 06:06

    For mysql,postgresql,oracle better way is SELF JOIN.

    Postgresql:
    DELETE FROM table t1 USING table t2 WHERE t1.date=t2.date AND t1.id<t2.id;
    
    MySQL        
    DELETE FROM table
    USING table, table as vtable
    WHERE (table.id < vtable.id)
    AND (table.date=vtable.date)
    

    SQL aggregate (max,group by) functions almost always are very slow.

    0 讨论(0)
  • 2020-11-27 06:08
    DELETE FROM table WHERE id NOT IN
        (SELECT MAX(id) FROM table GROUP BY date);
    
    0 讨论(0)
  • 2020-11-27 06:21

    I don't have comment rights, so here's my comment as an answer in case anyone comes across the same problem:

    In SQLite3, there is an implicit numerical primary key called "rowid", so the same query would look like this:

    DELETE FROM table WHERE rowid NOT IN
    (SELECT MAX(rowid) FROM table GROUP BY date);
    

    this will work with any table even if it does not contain a primary key column called "id".

    0 讨论(0)
提交回复
热议问题