MySQL queries several SQL statements with repeated records in the database

Source: Internet
Author: User

1. Query duplicate records based on a single field (name) in the table


SELECT * FROM user WHERE name IN (SELECT name FROM user group by name having count (name)> 1 );

2. Delete duplicate records based on a single field (name) in the table. Only records with the minimum id are retained.


Delete from user WHERE name IN (SELECT name FROM user group by name having count (name)> 1) AND id not in (SELECT min (id) FROM user group by name having count (name)> 1 );

3. Query duplicate records based on multiple fields (name, age) in the table


SELECT * FROM user u WHERE (u. name, u. age) IN (SELECT name, age FROM user group by name, age having count (*)> 1 );

4. Delete duplicate records based on multiple fields (name, age) in the table. Only records with the minimum id are retained.


Delete from user u WHERE (u. name, u. age) IN (SELECT name, age FROM user group by name, age having count (*)> 1) AND id not in (SELECT min (id) FROM user group by name, age having count (*)> 1 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.