mysql 如何去重

 

sql代碼:

去除重複:


delete  FROM  test where id NOT in(  select id FROM tmp  )


create table tmp (select id FROM test GROUP BY `name` )

tmp是創建的臨時表,不需要提前創建,直接寫接好,

爲什麼要創建臨時表,看下面:

直接寫會報錯 :  

delete  FROM  test where id NOT in(  select id FROM test GROUP BY `name`  )

[SQL]

delete  FROM  test where id NOT in(  select id FROM test GROUP BY `name`  )

[Err] 1093 - You can't specify target table 'test' for update in FROM clause

 

要先運行create table tmp (select id FROM test GROUP BY `name` ) 

先創建臨時表,才能查詢

 

去除重複保留最大ID:

DELETE a FROM  test a JOIN 
( SELECT  `name`, count(*), MAX(id) AS id FROM test GROUP BY name HAVING COUNT(*) > 1) b ON a.name = b.name WHERE a.id < b.id 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章