1. 程式人生 > >MySQL中刪除表中重複資料,只保留一條

MySQL中刪除表中重複資料,只保留一條

以為通過命令直接刪除就可以了,總是報錯:


delete from test


where name in(select name from test as t having count(name)>1)

發現在這隻能建立臨時表格,方法1設計可行:

1. 首先先建立一個臨時表,然後將author表中無重複的資料拎出來,放進臨時表中。
create temporary table 表名
select distinct id,name,password 
from author

然後將author表中的記錄全部刪除。
delete from author

最後將臨時表中的記錄插入author表中
insert into author (id,name,password)


select id,name,password 
from 臨時表

2.方法2直接使用語句:

delete from test
where name in(select t.name from (select name from test) as t having count(t.name)>1)
and name not in(select min(id) from(select id,name from test group by name)as tt having count(tt.name)>1)

發現總是刪錯資料,還未得到驗證這種查詢是否可行