MySQL 刪除重複資料
MySQL 刪除重複資料
找出重複:
SELECT * FROM `department_detail` GROUP BY `user_id` HAVING COUNT( * ) >1
刪除重複資料:
ALTER IGNORE TABLE `department_detail` ADD UNIQUE INDEX(`user_id`);#透過index限制達到刪除資料效果
ALTER TABLE department_detail DROP INDEX user_id; #刪除index限制
8 thoughts on “MySQL 刪除重複資料”
每日一SQL-刪除重複資料
https://dotblogs.com.tw/lastsecret/2010/07/13/16532
每一個項目只下一筆的搜尋
Select * From [Product] Where ID In (Select Max(ID) From [Product] Group By 產品名稱)
刪除的話,就是顛倒條件
DELETE Product where ID NOT IN (Select Max(ID) From [Product] Group By 產品名稱)
相同語法教學
http://gowintony.blogspot.com/2017/09/sql-server_26.html
MySQL刪除重複資料的解決方案
https://www.itread01.com/content/1543919114.html
情況01.[兩行資料完全相同]
1.查出表中所有行,不顯示重複行。
SELECT DISTINCT * FROM 原表
2.建立一張臨時表,儲存查到的新表資料。
CREATE TABLE 臨時表 AS (SELECT DISTINCT * FROM 原表);
3.刪除原表資料
DELETE FROM 原表;
4.把臨時表的資料插入到原表中。
INSERT INTO 原表 (SELECT * FROM 臨時表);
5.刪除臨時表
DROP TABLE 臨時表;
MySQL刪除重複資料的解決方案
https://www.itread01.com/content/1543919114.html
情況02.[某欄位相同]
1.查出表中有重複的行。
SELECT * FROM 原表 GROUP BY 欄位1 HAVING COUNT(欄位1)>1
2.建立一張臨時表,唯一地儲存有重複的資料。
CREATE TABLE 臨時表 AS (SELECT * FROM 原表 GROUP BY 欄位1 HAVING COUNT(欄位1)>1);
3.刪除原表中所有重複的資料
DELETE FROM 原表 WHERE 欄位1 IN ( SELECT * FROM (SELECT 欄位1 FROM 原表 GROUP BY 欄位1 HAVING COUNT(欄位1) > 1) 別名 )
4.把臨時表的唯一重複資料插入到原表中。
INSERT INTO 原表 (SELECT * FROM 臨時表);
5.刪除臨時表
DROP TABLE 臨時表;
MySQL刪除重複資料的解決方案
https://www.itread01.com/content/1543919114.html
情況03.[id不同,其他欄位相同]
1.查出所有記錄的最大id(這樣就可以過濾掉其他id不同的相同記錄),根據任意一個欄位分類。(這樣查出來的記錄就是無重複的整表記錄)
SELECT * FROM ( SELECT MAX(id) FROM 原表 GROUP BY 欄位1) 別名
2.刪除不在記錄中的資料(重複的資料)
DELETE FROM 原表 WHERE id NOT IN ( SELECT * FROM ( SELECT MAX(id) FROM 原表 GROUP BY 欄位1) 別名 )
SQL中刪除重複數據問題
https://mp.weixin.qq.com/s/PRiu-yWoxt82Kac_tWZQfQ
01.創建測試數據
CREATE TABLE [dbo].[Person](
[ID] [INT] IDENTITY(1,1) NOT NULL,
[Name] [VARCHAR](20) NULL,
[Age] [INT] NULL,
[Address] [VARCHAR](20) NULL,
[Sex] [CHAR](2) NULL
);
SET IDENTITY_INSERT [dbo].[Person] ON;
INSERT INTO [dbo].[Person] (ID,Name,Age,Address,Sex)
VALUES
( 1, ‘张三’, 18, ‘北京路18号’, ‘男’ ),
( 2, ‘李四’, 19, ‘北京路29号’, ‘男’ ),
( 3, ‘王五’, 19, ‘南京路11号’, ‘女’ ),
( 4, ‘张三’, 18, ‘北京路18号’, ‘男’ ),
( 5, ‘李四’, 19, ‘北京路29号’, ‘男’ ),
( 6, ‘张三’, 18, ‘北京路18号’, ‘男’ ),
( 7, ‘王五’, 19, ‘南京路11号’, ‘女’ ),
( 8, ‘马六’, 18, ‘南京路19号’, ‘女’ );
SET IDENTITY_INSERT [dbo].[Person] OFF;
02.找出重複的數據
SELECT MAX(ID) ID ,
Name,Age,Address,Sex
FROM dbo.Person
GROUP BY Name,Age,Address,Sex
HAVING COUNT(1)>1
03.刪除重複的數據
DELETE FROM Person
WHERE EXISTS
(
SELECT * FROM (
SELECT
MAX(ID) ID,
Name,Age,Address,Sex
FROM dbo.Person
GROUP BY Name,Age,Address,Sex
HAVING COUNT(1)>1) T
WHERE Person.Name=T.Name
AND Person.Age=T.Age
AND Person.Address=T.Address
AND Person.Sex=T.Sex
AND Person.ID
)