Home > Database > Mysql Tutorial > body text

Mysql deletes duplicate data and keeps the smallest ID

一个新手
Release: 2017-10-13 10:11:18
Original
2082 people have browsed it

Find and delete duplicate data on the Internet and keep the data with the smallest ID. The method is as follows:


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
)
Copy after login

When you use it yourself, an error message is displayed:


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

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

I don’t know what the cause is yet.

Then find a way to distribute the operations, first filter out the data with duplicate users, and then use max() to select the larger row:

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

Then delete the redundant data one by one based on the obtained max(id)


1 delete from tb where id=xx
Copy after login

The above is the detailed content of Mysql deletes duplicate data and keeps the smallest ID. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!