用于查找重复元组并显示计数的 MySQL 查询?
要查找重复元组,请使用 GROUP BY HAVING 子句。我们首先创建一个表 -
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.80 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(101,'David'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(101,'Mike'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(100,'Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable;
这将生成以下输出 -
+------+-------+ | Id | Name | +------+-------+ | 100 | Chris | | 101 | David | | 101 | Mike | | 100 | Carol | | 100 | Chris | | 100 | Chris | +------+-------+ 6 rows in set (0.00 sec)
以下是查找重复元组的查询 -
mysql> select Id,Name,count(*) as t from DemoTable -> group by Id,Name -> having count(*) > 2;
这将生成以下输出 -
+------+-------+---+ | Id | Name | t | +------+-------+---+ | 100 | Chris | 3 | +------+-------+---+ 1 row in set (0.03 sec)
广告