SQLite how to remove all duplicated rows except one?

十年热恋 提交于 2020-01-14 09:47:26

问题


I have a weird table call mytable, no column is primary.

  Name    |  Company  |  Position
 Michael     Google      Tester
 Michael     Google      Tester
 Michael     Google      Tester
 Peter       Facebook    Developer
 Peter       Facebook    Developer
 Peter       Facebook    Developer
 Peter       Facebook    Developer

What I want

  Name    |  Company  |  Position
 Michael     Google      Tester
 Peter       Facebook    Developer 

With some solutions I found with the same question here, they did not work. For example: DELETE FROM mytable WHERE Name NOT IN (SELECT MAX(Name) FROM mytable GROUP BY Company);

I should edit right in this table, use SQLite, no new table creation and no CTE. How can I do it?


回答1:


You can choose to keep the min or max of rowid grouping by the 3 columns shown.

delete from myTable
where rowid not in (select min(rowid)
                    from myTable
                    group by name,company,position)



回答2:


SELECT DISTINCT  Name,  Company,  Position 
FROM yourTableName

In case you want to delete "duplicate" rows you might write this:

yourTableName - should be your real database table

yourColumn - should be your real database column

DELETE FROM yourTableName
WHERE yourColumn NOT IN (
    SELECT yourColumn 
    FROM yourTableName
    WHERE yourColumn IS NOT NULL
)



回答3:


Hope this Solution works for you:

ALTER IGNORE TABLE mytable ADD UNIQUE INDEX (Name, Company, Position);



来源:https://stackoverflow.com/questions/45215241/sqlite-how-to-remove-all-duplicated-rows-except-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!