在 MySQL 中显示出现次数超过两次的记录?
为此,你可以使用 GROUP BY HAVING 子句。让我们先创建一个表 -
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Subject varchar(100) -> ); Query OK, 0 rows affected (0.53 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable(Subject) values('MySQL'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Subject) values('MongoDB'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(Subject) values('MySQL'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Subject) values('Java'); Query OK, 1 row affected (0.56 sec) mysql> insert into DemoTable(Subject) values('SQL Server'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Subject) values('MongoDB'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Subject) values('MySQL'); Query OK, 1 row affected (0.48 sec)
使用 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)
广告