显示 MySQL 中出现两次以上的记录?
为此,您可以使用GROUPBYHAVING子句。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Subject varchar(100) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Subject) values('MySQL'); mysql> insert into DemoTable(Subject) values('MongoDB'); mysql> insert into DemoTable(Subject) values('MySQL'); mysql> insert into DemoTable(Subject) values('Java'); mysql> insert into DemoTable(Subject) values('SQL Server'); mysql> insert into DemoTable(Subject) values('MongoDB'); mysql> insert into DemoTable(Subject) values('MySQL');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;输出结果
+----+------------+ | Id | Subject | +----+------------+ | 1 | MySQL | | 2 | MongoDB | | 3 | MySQL | | 4 | Java | | 5 | SQL Server | | 6 | MongoDB | | 7 | MySQL | +----+------------+ 7 rows in set (0.00 sec)
以下是显示在MySQL中出现次数超过2次的不同记录的查询。
mysql> select Subject,count(Subject) freq from DemoTable -> group by Subject -> having count(Subject) > 2;输出结果
+---------+------+ | Subject | freq | +---------+------+ | MySQL | 3 | +---------+------+ 1 row in set (0.00 sec)