首页 > 代码库 > MySQL中删除重复数据只保留一条
MySQL中删除重复数据只保留一条
用SQL语句,删除掉重复项只保留一条
在几千条记录里,存在着些相同的记录,如何能用SQL语句,删除掉重复的呢
1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断
SELECT
*
FROM
people
WHERE
peopleId IN (
SELECT
peopleId
FROM
people
GROUP BY
peopleId
HAVINGcount(peopleId) > 1
)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录
DELETEFROM
people
WHERE
peopleName IN (
SELECT
peopleName
FROM
people
GROUP BY
peopleName
HAVINGcount(peopleName) > 1
)
AND peopleId NOT IN (
SELECTmin(peopleId)
FROM
people
GROUP BY
peopleName
HAVINGcount(peopleName) > 1
)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
3、查找表中多余的重复记录(多个字段)
SELECT
*
FROM
vitae a
WHERE
(a.peopleId, a.seq) IN (
SELECT
peopleId,
seq
FROM
vitae
GROUP BY
peopleId,
seq
HAVINGcount(*) > 1
)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录
DELETEFROM
vitae a
WHERE
(a.peopleId, a.seq) IN (
SELECT
peopleId,
seq
FROM
vitae
GROUP BY
peopleId,
seq
HAVINGcount(*) > 1
)
AND rowid NOT IN (
SELECTmin(rowid)
FROM
vitae
GROUP BY
peopleId,
seq
HAVINGcount(*) > 1
)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录
SELECT
*
FROM
vitae a
WHERE
(a.peopleId, a.seq) IN (
SELECT
peopleId,
seq
FROM
vitae
GROUP BY
peopleId,
seq
HAVINGcount(*) > 1
)
AND rowid NOT IN (
SELECTmin(rowid)
FROM
vitae
GROUP BY
peopleId,
seq
HAVINGcount(*) > 1
)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
6.消除一个字段的左边的第一位:
UPDATE tableName
SET [ Title ]= RIGHT ([ Title ],(len([ Title ]) - 1))
WHERE
Title LIKE ‘村%‘
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
7.消除一个字段的右边的第一位:
UPDATE tableName
SET [ Title ]= LEFT ([ Title ],(len([ Title ]) - 1))
WHERE
Title LIKE ‘%村‘
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
8.假删除表中多余的重复记录(多个字段),不包含rowid最小的记录
UPDATE vitae
SET ispass =- 1WHERE
peopleId IN (
SELECT
peopleId
FROM
vitae
GROUP BY
peopleId
来源: http://blog.csdn.net/z_youarethebest/article/details/53785435
来自为知笔记(Wiz)
MySQL中删除重复数据只保留一条
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。