在實(shí)際開發(fā)中,可能會(huì)遇到數(shù)據(jù)庫(kù)多條數(shù)據(jù)重復(fù)了,此時(shí)我們需要?jiǎng)h除重復(fù)數(shù)據(jù),只保留一條有效數(shù)據(jù),用SQL語(yǔ)句怎么實(shí)現(xiàn)呢,下面我們模擬一下:
1.準(zhǔn)備重復(fù)數(shù)據(jù):
2.過(guò)濾出存在重復(fù)數(shù)據(jù)的信息:
SQL語(yǔ)句:
SELECT
dname
FROM
dept
GROUP BY
dname
HAVING
count( dname ) >1
數(shù)據(jù)庫(kù)篩選結(jié)果:
3.從重復(fù)數(shù)據(jù)中篩選出一條需要保存的數(shù)據(jù):
SQL語(yǔ)句:
SELECT
min( deptno ) -- max( deptno )
FROM
dept
GROUP BY
dname
HAVING
count( dname ) >1
這里使用數(shù)據(jù)庫(kù)的MIN或者M(jìn)AX函數(shù)篩選出一條需要保存數(shù)據(jù)即可。
數(shù)據(jù)庫(kù)篩選結(jié)果:
4.刪除重復(fù)數(shù)據(jù),即從重復(fù)的數(shù)據(jù)中,刪除掉需要保留數(shù)據(jù)之外的所有信息:
SQL:
DELETE
FROM
dept
WHERE
dname IN ( SELECT dname FROM dept GROUP BY dname HAVING count( dname ) > 1 ) -- 過(guò)濾出重復(fù)的dname
AND deptno NOT IN ( SELECT min( deptno ) AS deptno FROM dept GROUP BY dname HAVING count( dname ) > 1 ) -- 過(guò)濾出不在需要保留的id之外的所有id
如果是oracle數(shù)據(jù)庫(kù),上面的SQL語(yǔ)句可以正常執(zhí)行,可是換成MySQL數(shù)據(jù)庫(kù),SQL語(yǔ)句執(zhí)行會(huì)報(bào)錯(cuò):
1093 - You can't specify target table 'dept' for update in FROM clause
含義:不能在同一表中查詢的數(shù)據(jù)作為同一表的更新數(shù)據(jù)。
適用于mysql數(shù)據(jù)庫(kù)的SQL:
DELETE
FROM
dept
WHERE
dname IN ( SELECT * FROM ( SELECT dname FROM dept GROUP BY dname HAVING count( dname ) > 1 ) a )
AND deptno NOT IN ( SELECT * FROM ( SELECT min( deptno ) AS deptno FROM dept GROUP BY dname HAVING count( dname ) > 1 ) b )
數(shù)據(jù)庫(kù)最后數(shù)據(jù):
到這里,刪除重復(fù)數(shù)據(jù)成功!
一顆安安靜靜的小韭菜。文中如果有什么錯(cuò)誤,歡迎指出。