要查找重复的元组,请使用GROUP BY HAVING子句。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(100,'Chris'); mysql> insert into DemoTable values(101,'David'); mysql> insert into DemoTable values(101,'Mike'); mysql> insert into DemoTable values(100,'Carol'); mysql> insert into DemoTable values(100,'Chris'); mysql> insert into DemoTable values(100,'Chris');
使用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)