Mysql-& gt; SQL statement: SQL statement used to delete duplicate data _ MySQL

Source: Internet
Author: User
Tags mysql code
Mysql-amp; gt; SQL statement to delete duplicate data bitsCN.com

Mysql-> SQL statement: delete duplicate data

A question frequently asked during the interview: an SQL statement is used to delete duplicate data in the table.

Occasionally, when I talked to my colleagues about this issue, I wrote the code for your reference ~

// Data preparation

Mysql code

Drop table t_user;

Create table t_user (

Id int (5) not null auto_increment,

Username varchar (10 ),

Age int (3 ),

Primary key (id)

);

Insert into t_user (username, age) values ('AAA', 20 );

Insert into t_user (username, age) values ('AAA', 20 );

Insert into t_user (username, age) values ('AAA', 20 );

Insert into t_user (username, age) values ('BBB ', 20 );

Insert into t_user (username, age) values ('BBB ', 20 );

Insert into t_user (username, age) values ('CCC ', 20 );

Insert into t_user (username, age) values ('CCC ', 20 );

Insert into t_user (username, age) values ('ddd ', 20 );

Insert into t_user (username, age) values ('ddd ', 20 );

Delete statement:

Mysql code

DELETE t

FROM

T_user t,

(

SELECT

Min (id) AS ttid,

Username

FROM

T_user t2

GROUP

T2.username

) AS tt

WHERE t. id> tt. ttid

And t. username = tt. username;

BitsCN.com

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.