为此,请使用GROUP BY HAVING子句。让我们首先创建一个表-
mysql> create table DemoTable( Name varchar(100), Age int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Chris',23); mysql> insert into DemoTable values('David',21); mysql> insert into DemoTable values('Chris',23); mysql> insert into DemoTable values('Chris',21); mysql> insert into DemoTable values('Mike',25); mysql> insert into DemoTable values('David',21);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-------+------+ | Name | Age | +-------+------+ | Chris | 23 | | David | 21 | | Chris | 23 | | Chris | 21 | | Mike | 25 | | David | 21 | +-------+------+ 6 rows in set (0.00 sec)
以下是查找重复行并在单独的列中显示计数的查询-
mysql> select Name,Age,count(*) AS Repeated from DemoTable group by Name,Age having Repeated > 1;
这将产生以下输出-
+-------+------+----------+ | Name | Age | Repeated | +-------+------+----------+ | Chris | 23 | 2 | | David | 21 | 2 | +-------+------+----------+ 2 rows in set (0.00 sec)