阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

MySQL中删除重复数据只保留一条

276次阅读
没有评论

共计 1339 个字符,预计需要花费 4 分钟才能阅读完成。

用 SQL 语句, 删除掉 MySQL 重复项只保留一条

在几千条记录里, 存在着些相同的记录, 如何能用 SQL 语句, 删除掉重复的呢
1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断

SELECT
    *
FROM
    people
WHERE
    peopleId IN (SELECT
            peopleId
        FROM
            people
        GROUP BY
            peopleId
        HAVING
            count(peopleId) > 1
    )

2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有 rowid 最小的记录

DELETE
FROM
    people
WHERE
    peopleName IN (SELECT
            peopleName
        FROM
            people
        GROUP BY
            peopleName
        HAVING
            count(peopleName) > 1
    )
AND peopleId NOT IN (SELECT
        min(peopleId)
    FROM
        people
    GROUP BY
        peopleName
    HAVING
        count(peopleName) > 1
)

3、查找表中多余的重复记录(多个字段)

SELECT
    *
FROM
    vitae a
WHERE
    (a.peopleId, a.seq) IN (SELECT
            peopleId,
            seq
        FROM
            vitae
        GROUP BY
            peopleId,
            seq
        HAVING
            count(*) > 1
    )

4、删除表中多余的重复记录(多个字段),只留有 rowid 最小的记录

DELETE
FROM
    vitae a
WHERE
    (a.peopleId, a.seq) IN (SELECT
            peopleId,
            seq
        FROM
            vitae
        GROUP BY
            peopleId,
            seq
        HAVING
            count(*) > 1
    )
AND rowid NOT IN (SELECT
        min(rowid)
    FROM
        vitae
    GROUP BY
        peopleId,
        seq
    HAVING
        count(*) > 1
)

5、查找表中多余的重复记录(多个字段),不包含 rowid 最小的记录

SELECT
    *
FROM
    vitae a
WHERE
    (a.peopleId, a.seq) IN (SELECT
            peopleId,
            seq
        FROM
            vitae
        GROUP BY
            peopleId,
            seq
        HAVING
            count(*) > 1
    )
AND rowid NOT IN (SELECT
        min(rowid)
    FROM
        vitae
    GROUP BY
        peopleId,
        seq
    HAVING
        count(*) > 1
)

6. 消除一个字段的左边的第一位:

UPDATE tableName
SET [Title]= RIGHT ([Title],(len([ Title]) - 1))
WHERE
    Title LIKE '村 %'

7. 消除一个字段的右边的第一位:

UPDATE tableName
SET [Title]= LEFT ([Title],(len([ Title]) - 1))
WHERE
    Title LIKE '% 村'

8. 假删除表中多余的重复记录(多个字段),不包含 rowid 最小的记录

UPDATE vitae
SET ispass =- 1
WHERE
    peopleId IN (SELECT
            peopleId
        FROM
            vitae
        GROUP BY
            peopleId

本文永久更新链接地址 :http://www.linuxidc.com/Linux/2016-12/138386.htm

正文完
星哥玩云-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-22发表,共计1339字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中