要仅从数据库中选择重复记录并显示计数,请使用HAVING以及聚合功能count()
。让我们首先创建一个表-
mysql> create table duplicateRecords -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20) -> );
以下是使用insert命令在表中插入记录的查询-
mysql> insert into duplicateRecords(ClientName) values('John'); mysql> insert into duplicateRecords(ClientName) values('Carol'); mysql> insert into duplicateRecords(ClientName) values('John'); mysql> insert into duplicateRecords(ClientName) values('Sam'); mysql> insert into duplicateRecords(ClientName) values('Sam'); mysql> insert into duplicateRecords(ClientName) values('Bob'); mysql> insert into duplicateRecords(ClientName) values('John'); mysql> insert into duplicateRecords(ClientName) values('Sam');
以下是使用select语句显示表中所有记录的查询-
mysql> select * from duplicateRecords;
这将产生以下输出-
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 1 | John | | 2 | Carol | | 3 | John | | 4 | Sam | | 5 | Sam | | 6 | Bob | | 7 | John | | 8 | Sam | +----------+------------+ 8 rows in set (0.00 sec)
以下是查询:仅从数据库中选择重复记录-
mysql> select ClientName,count(*) as DuplicateRecord -> from duplicateRecords -> group by ClientName -> having DuplicateRecord > 1;
这将产生以下输出-
+------------+-----------------+ | ClientName | DuplicateRecord | +------------+-----------------+ | John | 3 | | Sam | 3 | +------------+-----------------+ 2 rows in set (0.00 sec)