1. 程式人生 > 實用技巧 >Mysql查重去重操作

Mysql查重去重操作

有這麼一張表:

裡面的技術重複了2次,採購重複了一次。

使用如下語句:

select * from test GROUP BY name HAVING COUNT(*) >1

效果如下:

可以看到返回的值與重複的次數不一樣。

select * from test where name in(select name from test GROUP BY name HAVING COUNT(name) >1);

使用這個語句,可以把所有name一樣的都返回。

效果如下:

select distinct name,code from test where name=0

使用上面的程式碼,可以將name,code欄位中重複的資料去除以後再返回,

效果如下:

select name,code from test where name=0 group by name

這個語句也是一樣的效果

SELECT * FROM test WHERE name IN (SELECT `name` from test GROUP BY `name` HAVING COUNT(1)>1) AND id NOT in (SELECT min(id) from test GROUP BY `name` HAVING count(1)>1)
SELECT * from
test where id not in (SELECT dt.minno from (SELECT MIN(id) as minno from test GROUP BY name)dt)

刪除多餘資料且只保留1條

delete from test where name in (SELECT t.name from (SELECT name from test GROUP BY name HAVING COUNT(1)>1)t) and id not in (SELECT dt.minno from (SELECT min(id) as minno from test GROUP BY name HAVING count(1)>1)dt)
DELETE FROM `test` WHERE id NOT IN(SELECT * FROM(SELECT id FROM `test` GROUP BY name)AS A)