在mysql中刪除重復(fù)數(shù)據(jù)的方法各千種,但我百度了N種刪除重復(fù)數(shù)據(jù)方法,個(gè)人測試小數(shù)據(jù)量還沒有問題,大數(shù)據(jù)量就卡死了,下面我來介紹超強(qiáng)刪除重復(fù)數(shù)據(jù)語句實(shí)例,各位朋友有興趣可參考.
月小升今天遇到的問題是students這個(gè)表有md這個(gè)字段重復(fù),看看如何處理吧,代碼如下:
- select * from students
- where md in (select md from students group by md having count(md) > 1) order by md
注明,這個(gè)被group的字段,請索引,否則很慢,代碼如下:
- delete from students
- where md in (select md from students group by md having count(md) > 1)
- and id not in (select min(id) from students group by md having count(md )>1)
這個(gè)語句在mysql下會(huì)報(bào)錯(cuò):#1093 – You can’t specify target table ‘students’ for update in FROM clause
原因是好像mysql不準(zhǔn)許我們進(jìn)行聯(lián)合刪除內(nèi)有條件語句指向自己的表,策略是使用臨時(shí)表,存儲(chǔ)那些要?jiǎng)h除的ID,代碼如下:
- create table tmp (id int);
- insert into tmp (id) select id from students
- where md in (select md from students group by md having count(md) > 1)
- and id not in (select min(id) from students group by md having count(md )>1); --Vevb.com
- delete from students where id in (select id from tmp);
得出會(huì)被刪除的數(shù)據(jù),代碼如下:
- select * from students
- where md in (select md from students group by md having count(md) > 1)
- and id not in (select min(id) from students group by md having count(md )>1)
得出過濾后的數(shù)據(jù),不刪除的數(shù)據(jù),如果不用刪除,此sql語句可以用來顯示唯一數(shù)據(jù),代碼如下:
- select * from students
- where
- id in (select min(id) from students group by md having count(md )>1)
新聞熱點(diǎn)
疑難解答
圖片精選