您可以在某种情况下使用DELETE命令,因为我们需要保留一条记录并删除其余的重复记录。
让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(40) );
使用插入命令在表中插入记录-
mysql> insert into DemoTable(StudentName) values('John'); mysql> insert into DemoTable(StudentName) values('Carol'); mysql> insert into DemoTable(StudentName) values('Sam'); mysql> insert into DemoTable(StudentName) values('Carol'); mysql> insert into DemoTable(StudentName) values('David'); mysql> insert into DemoTable(StudentName) values('Carol');
使用选择命令显示表中的记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 4 | Carol | | 5 | David | | 6 | Carol | +-----------+-------------+ 6 rows in set (0.00 sec)
这是删除单个记录以外的重复记录的查询-
mysql> delete tbl1 from DemoTable tbl1,DemoTable tbl2 WHERE tbl1.StudentName = tbl2.StudentName AND tbl1.StudentId > tbl2.StudentId;
上面的查询删除了“ Carol”的2行,并保留了“ Carol”记录之一。
现在让我们显示表的记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 5 | David | +-----------+-------------+ 4 rows in set (0.00 sec)