要删除重复项并在表中保留一行,您需要使用临时表的概念。步骤如下-
create table anytemporaryTableName as select distinct yourColumnName1, yourColumnName2 from yourTableName; truncate table yourTableName; insert into yourTableName(yourColumnName1, yourColumnName2) select yourColumnName1, yourColumnName2 from yourtemporaryTableName ; drop table yourtemporaryTableName ;
让我们创建一个表-
mysql> create table demo39 −> ( −> user_id int, −> user_name varchar(20) −> );
借助insert命令将一些记录插入表中-
mysql> insert into demo39 values(10,'John'); mysql> insert into demo39 values(10,'John'); mysql> insert into demo39 values(11,'David'); mysql> insert into demo39 values(11,'David');
使用select语句显示表中的记录-
mysql> select *from demo39;
这将产生以下输出-
+---------+-----------+ | user_id | user_name | +---------+-----------+ | 10 | John | | 10 | John | | 11 | David | | 11 | David | +---------+-----------+ 4 rows in set (0.00 sec)
以下是删除重复项并在表中保留一行的查询-
mysql> create table temporaryTable as select distinct user_id, user_name from demo39; Records: 2 Duplicates: 0 Warnings: 0 mysql> truncate table demo39; mysql> insert into demo39(user_id, user_name) select user_id, user_name from temporaryTable; Records: 2 Duplicates: 0 Warnings: 0 mysql> drop table temporaryTable;
使用select语句显示表中的记录-
mysql> select *from demo39;
这将产生以下输出-
+---------+-----------+ | user_id | user_name | +---------+-----------+ | 10 | John | | 11 | David | +---------+-----------+ 2 rows in set (0.00 sec)