MySQL Find delete duplicate data and keep only one instance detailed _php instance

Source: Internet
Author: User

There is such a table, the table data and the results are as follows:

school_id School_name Total_student Test_takers
1239 Abraham Lincoln High School 55 50
1240 Abraham Lincoln High School 70 35
1241 Acalanes High School 120 89
1242 Academy of the Canyons 30 30
1243 Agoura High School 89 40
1244 Agoura High School 100 50

We can see that School_name's field values have duplicate data (Abraham Lincoln High School and Agoura High School appear two), so how do you delete the two data so that only the two values appear once? The implementation methods are as follows:

1, delete duplicate records, save the least ID of the one

Delete from ' test ' WHERE ' school_name ' (SELECT ' school_name ', '
test ' 
GROUP by ' School_name ' has 
cou NT (*) >1) and school_id not in (select min (school_id) from test group by SCHOOL_ID have Count (*) >1)

Use the group by has syntax to query for duplicate data, and then delete the duplicate data and keep the school_id of the smallest one.

2, delete the duplicate record, save the largest one of the ID

Delete from ' test ' WHERE ' school_name ' (SELECT ' school_name ', '
test ' 
GROUP by ' School_name ' has 
cou NT (*) >1) and school_id not in (select Max (school_id) from test group by SCHOOL_ID have Count (*) >1)

The principle is the same as above.

The above is the MySQL find delete duplicate data and only keep one instance detailed, hope to help everyone, thank you for the support of this site!

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.