如何在 MySQL 中找出重复行并在单独列中显示其计数?
为此,请使用 GROUP BY HAVING 子句。我们首先创建一个表 −
mysql> create table DemoTable( Name varchar(100), Age int ); Query OK, 0 rows affected (1.50 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Chris',23); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('David',21); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris',23); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Chris',21); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values('Mike',25); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('David',21); Query OK, 1 row affected (0.10 sec)
使用 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)
广告