若要选择重复项,可以使用子查询。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Name) values('John'); mysql> insert into DemoTable(Name) values('Chris'); mysql> insert into DemoTable(Name) values('John'); mysql> insert into DemoTable(Name) values('David'); mysql> insert into DemoTable(Name) values('Bob'); mysql> insert into DemoTable(Name) values('Chris'); mysql> insert into DemoTable(Name) values('Mike'); mysql> insert into DemoTable(Name) values('Robert'); mysql> insert into DemoTable(Name) values('Mike');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
+----+--------+ | Id | Name | +----+--------+ | 1 | John | | 2 | Chris | | 3 | John | | 4 | David | | 5 | Bob | | 6 | Chris | | 7 | Mike | | 8 | Robert | | 9 | Mike | +----+--------+ 9 rows in set (0.00 sec)
以下是选择所有重复项的查询-
mysql> select *from DemoTable -> where Name in (select Name from DemoTable group by Name having count(*) > 1);
输出结果
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Chris | | 3 | John | | 6 | Chris | | 7 | Mike | | 9 | Mike | +----+-------+ 6 rows in set (0.09 sec)