为此,请使用合计函数COUNT()
和GROUP BY对这些特定记录进行分组。让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentSubject varchar(40) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(StudentSubject) values('MySQL'); mysql> insert into DemoTable(StudentSubject) values('Java'); mysql> insert into DemoTable(StudentSubject) values('MySQL'); mysql> insert into DemoTable(StudentSubject) values('MongoDB'); mysql> insert into DemoTable(StudentSubject) values('Java');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+----------------+ | StudentId | StudentSubject | +-----------+----------------+ | 1 | MySQL | | 2 | Java | | 3 | MySQL | | 4 | MongoDB | | 5 | Java | +-----------+----------------+ 5 rows in set (0.00 sec)
以下是对一个MySQL查询中特定记录(重复)的出现进行统计的查询-
mysql> select StudentSubject,count(StudentId) from DemoTable group by StudentSubject;
这将产生以下输出-
+----------------+------------------+ | StudentSubject | count(StudentId) | +----------------+------------------+ | MySQL | 2 | | Java | 2 | | MongoDB | 1 | +----------------+------------------+ 3 rows in set (0.00 sec)