欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

Mysql删除重复数据保留最小的id

程序员文章站 2022-04-22 19:21:37
...
在网上查找删除重复数据保留id最小的数据,方法如下:


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
)

自己使用的时候显示报错:


1 delete from tb where id in (SELECT max(id) from tb GROUP BY user HAVING count(user)>1)

[Err] 1093 - You can't specify target table ‘XXX’ for update in FROM clause

暂时不知道是什么原因导致的。

然后想办法分布操作,首先筛选出有重复user的数据,然后用max()选出其中较大的那一行:

SELECT max(id) from tb GROUP BY user HAVING count(user)>1

然后再根据得到的max(id)逐条删除多余的数据


1 delete from tb where id=xx

以上就是Mysql删除重复数据保留最小的id的详细内容,更多请关注其它相关文章!