在實際工作開發(fā)過程中,常常會遇到數(shù)據(jù)庫表中存在多條數(shù)據(jù)重復(fù)了,此時我們需要刪除重復(fù)數(shù)據(jù),只保留其中一條有效的數(shù)據(jù);
針對這種場景,我們用SQL語句該怎么實現(xiàn)呢?
數(shù)據(jù)準(zhǔn)備
建表語句:
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` int(11) NULL DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `test` VALUES (1, '張三');
INSERT INTO `test` VALUES (2, '李四');
INSERT INTO `test` VALUES (4, '張三');
INSERT INTO `test` VALUES (5, '王二');
INSERT INTO `test` VALUES (6, '護具');
INSERT INTO `test` VALUES (7, '無極');
INSERT INTO `test` VALUES (8, '護具');
INSERT INTO `test` VALUES (3, '空氣');
INSERT INTO `test` VALUES (9, '王二');
INSERT INTO `test` VALUES (10, '幾乎');
commit;
查看重復(fù)數(shù)據(jù),并篩選
select t.name,count(1) from test t where 1=1 group by t.name ;
使用having語句進行篩選
select t.name,count(1) from test t where 1=1 group by t.name HAVING count(1) >1;
對于重復(fù)數(shù)據(jù),保留一條數(shù)據(jù)篩選
select t.name,min(id) as id ,count(1) from test t where 1=1 group by t.name;
刪除重復(fù)數(shù)據(jù)
delete from test where id not in (
select min(id) from test t where 1=1 group by t.name ) ;
執(zhí)行上述SQL語句,發(fā)現(xiàn)會報錯:
delete from test where id not in (
select min(id) from test t where 1=1 group by t.name )
> 1093 - You can't specify target table 'test' for update in FROM clause
> 時間: 0.004s
導(dǎo)致這一原因的問題是:不能在同一表中查詢的數(shù)據(jù)作為同一表的更新數(shù)據(jù)。
正確參考SQL:
(1) 創(chuàng)建一張表temp_table存儲最終保留的數(shù)據(jù)。
create table temp_table as SELECT min( id ) as id FROM test t WHERE 1 = 1 GROUP BY t.NAME;
(2) 排除表temp_table中的數(shù)據(jù),刪除即可。
DELETE FROM test WHERE id NOT IN (SELECT * FROM temp_table);
成功刪除重復(fù)數(shù)據(jù)!文章來源:http://www.zghlxwxcb.cn/news/detail-683795.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-683795.html
到了這里,關(guān)于MySQL怎樣刪除重復(fù)數(shù)據(jù),只保留一條?的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!