MySQL Database super Strong delete duplicate data statement

Source: Internet
Author: User

The problem with students today is that this table has MD this field to repeat. See how to deal with it.

The code is as follows Copy Code

SELECT * FROM Students
Where MD in (select MD from Students GROUP by MD have COUNT (MD) > 1) ORDER by MD

Note that this group of fields, please index, otherwise very slow

The code is as follows Copy Code
Delete from students
Where MD in (select MD from Students GROUP by MD have COUNT (MD) > 1)
and ID not in (select min (ID) from students GROUP by MD have COUNT (MD) >1)

This statement will be an error under MySQL

#1093 –you can ' t specify target table ' students ' for update in FROM clause

The reason is as if MySQL does not allow us to make joint deletes the conditional statement points to its own table.

The policy is to use temporary tables to store the IDs that are to be deleted

The code is as follows Copy Code

CREATE TABLE tmp (ID int);

INSERT into TMP (ID) Select ID from students
Where MD in (select MD from Students GROUP by MD have COUNT (MD) > 1)
and ID not in (the Select min (ID) from students GROUP by MD have COUNT (MD) >1);

Delete from students where ID in (SELECT ID from TMP);

Get the data that will be deleted

The code is as follows Copy Code

SELECT * FROM Students
Where MD in (select MD from Students GROUP by MD have COUNT (MD) > 1)
and ID not in (select min (ID) from students GROUP by MD have COUNT (MD) >1)

The filtered data is obtained without deleting the data. If not removed, this SQL statement can be used to display unique data

/tbody>
  code is as follows copy code

Select * From students
where
ID in (select min (ID) from students GROUP by MD has COUNT (MD) >1)

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.