仅从数据库中选择重复记录,同时显示其数量?
要仅从数据库中选择重复记录并显示其数量,请使用 HAVING 和聚合函数 count()。让我们首先创建一个表-。
mysql> create table duplicateRecords -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20) -> ); Query OK, 0 rows affected (0.49 sec)
以下是使用 insert 命令向表中插入记录的查询-。
mysql> insert into duplicateRecords(ClientName) values('John'); Query OK, 1 row affected (0.16 sec) mysql> insert into duplicateRecords(ClientName) values('Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into duplicateRecords(ClientName) values('John'); Query OK, 1 row affected (0.29 sec) mysql> insert into duplicateRecords(ClientName) values('Sam'); Query OK, 1 row affected (0.19 sec) mysql> insert into duplicateRecords(ClientName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into duplicateRecords(ClientName) values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into duplicateRecords(ClientName) values('John'); Query OK, 1 row affected (0.13 sec) mysql> insert into duplicateRecords(ClientName) values('Sam'); Query OK, 1 row affected (0.12 sec)
以下是使用 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)
广告