与该COUNT()
方法一起使用GROUP BY 。将名称与GROUP BY分组,然后使用COUNT()
方法进行计数。让我们首先创建一个表-
mysql> create table DemoTable ( Name varchar(30) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Chris'); mysql> insert into DemoTable values('Robert'); mysql> insert into DemoTable values('Mike'); mysql> insert into DemoTable values('Robert'); mysql> insert into DemoTable values('Mike'); mysql> insert into DemoTable values('David');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+ | Name | +--------+ | Chris | | Robert | | Mike | | Robert | | Mike | | David | +--------+ 6 rows in set (0.00 sec)
以下是按名称分组并显示计数的查询-
mysql> select Name,count(Name) as NumberOfRowsPerName from DemoTable group by Name;
这将产生以下输出-
+--------+---------------------+ | Name | NumberOfRowsPerName | +--------+---------------------+ | Chris | 1 | | Robert | 2 | | Mike | 2 | | David | 1 | +--------+---------------------+ 4 rows in set (0.00 sec)