MySQL Delete duplicate data only keep one bar

Source: Internet
Author: User

Interview encounter a MySQL interesting topic, how to remove duplicate name row from student table, and keep record of minimum ID?

Unfortunately didn't do it at that time, home search, found that the use of sub-query can be quickly resolved.

1, delete redundant records in the table, duplicate records is username judgment, leaving only the record with the smallest ID

Delete  fromStudentwhereusernameinch(SelectUsername fromStudentgroup byUsername having Count(username)>1) andId not inch(Select min(ID) asId fromStudentgroup byUsername having Count(username)>1)

(The above statement is executed in MySQL with an error:

Execution error: 1093-you can ' t specify target table ' student ' for update in FROM clause

The reason is that the query is used when updating the data, and the data of the query is updated again, andMySQL does not support this approach. Both Oracel and msserver support this approach.

How to circumvent this problem?

Plus a layer of encapsulation,

Delete  fromStudentwhereusernameinch(SelectUsername from(SelectUsername fromStudentGroup  byUsername having Count(username)>1) a) andId not inch(SelectId from(Select min(ID) asId fromStudentGroup  byUsername having Count(username)>1) b)

Note Select min (ID) is followed by an as ID.

There are more simple ways to do this (for a single field):

Delete  from where   not in ( Select from (selectmin as from (group by username) b);

Expand:

2.Delete extra duplicate records (multiple fields) in the table, leaving only the record with the smallest ID

Delete  fromStudent Awhere(A.USERNAME,A.SEQ)inch(SelectUsername,seq from(SelectUsername,seq fromAGroup  byUsername,seq having Count(*)> 1) t1) andId not inch(SelectId from(Select min(ID) fromVitaeGroup  byUsername,seq having Count(*)>1) T2)

Reference article:

6407280

MySQL Delete duplicate data only keep one bar

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.