SQL statement that removes duplicate records in MySQL and preserves one piece of data in duplicate data

Source: Internet
Author: User

Just want to write a delete duplicate statement and keep a data of SQL, online check a part of the information written in very detailed, but still here to write their own understanding, in order to follow the study. As follows:


Table fields and data:


SQL statements:

[SQL]View PlainCopy
  1. DELETE from `User` WHEREID notinch(SELECT *  from(SELECTID from `User` GROUP byusername) asb)

Understand:

Let's start with the SQL inside.

1.SELECT ID from the ' user ' GROUP by username the ID of each group based on the name group.

2.SELECT * FROM (SELECT ID from ' user ' GROUP by username) as B There are 2 questions in this sentence,

First, why do you want to set such a select? MySQL does not support this approach because the query is used to update the data, and the queried data is updated again.

If this select query is not set, then the 1093-you can ' t specify target table ' user ' for update on FROM clause error will be reported.

Second, this sentence must take the alias, otherwise it will be reported 1248-every derived table must has its own alias error

3, combined with the above analysis to look at the entire SQL statement understanding, first to find out the group ID, and then delete the user table in the ID is not in the group ID of the data, then realize the effect.

Delete from table name where ID not in (column name of the Select ID from table name Group by group) alias


The effect is as follows:

Turn from:http://blog.csdn.net/dsiori/article/details/52806709

SQL statement that removes duplicate records in MySQL and preserves one piece of data in duplicate data

Related Article

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.