2013-10-02 118 views
1

我有以下查詢基本上找到自己的用戶名列中的所有副本:刪除重複在一列

SELECT `username` 
FROM `instagram_user` 
GROUP BY `username` 
HAVING COUNT(*) >1 

如何刪除所有的重複,這樣只會讓我用一個唯一的用戶名中桌子?只要表中有一個唯一的用戶名,我不關心哪個實體被持久或刪除。

+1

您使用了什麼引擎(MyISAM,InnoDB,...)?你有一些'id'專欄嗎?更好,但張貼您的表架構 – peterm

+1

另請參閱http://stackoverflow.com/questions/3311903/remove-duplicate-rows-in-mysql?rq=1 – Thilo

+0

@peterm是的我有每個用戶名的id,它只是ID和用戶名..使用MyISAM – adit

回答

2

如果你不在乎什麼紀錄選擇然後只是添加一個唯一的約束,而使用IGNORE

ALTER IGNORE TABLE instagram_user ADD UNIQUE (username); 

這裏是SQLFiddle演示

和MySQL會爲你做這項工作。無論如何,您都希望擁有唯一的約束條件,以便將來您的表格不會出現重複。

或者你也可以做

DELETE t 
    FROM instagram_user t JOIN 
(
    SELECT username, MAX(id) id 
    FROM instagram_user 
    GROUP BY username 
    HAVING COUNT(*) > 1 
) q 
    ON t.username = q.username 
    AND t.id <> q.id 

這一次將只留下與最大ID一排具有重複的用戶名行。

這裏是SQLFiddle演示

0

不確定這是否適用於SQL Server,您可以嘗試在mysql中使用類似的代碼。

;With CteUsers AS(

SELECT *,ROW_NUMBER() OVER (PARTITION BY username Order by username) AS ROWID 
FROM(

SELECT PkId, `username` 
FROM `instagram_user` 
)tbltemp) 
SELECT * FROM CteUsers; 

這將導致如下

PkId username RowId 
1  xx  1 
2  xx  2 
.... 

然後刪除其中RowId的> 1

;隨着CteUsers AS(

SELECT *,ROW_NUMBER() OVER (PARTITION BY username Order by username) AS ROWID 
    FROM(

    SELECT PkId, `username` 
    FROM `instagram_user` 
    )tbltemp) 
    DELETE instagram_user WHERE PkId iN (SELECT PkId FROM CteUsers WHERE ROWID > 1); 
0

這會給你的副本(即你需要刪除的)...

select a.id, a.username from instagram_user a, instagram_user b 
where a.username = b.username and a.id <> b.id 
    and b.id = (select min(id) from instagram_user where username = a.username) 

所以DELETE會是這樣的......

delete from instagram_user where id in 
(select a.id from instagram_user a, instagram_user b 
    where a.username = b.username and a.id <> b.id 
     and b.id = (select min(c.id) from instagram_user c 
        where c.username = a.username))