您需要为此使用GROUP BY。让我们首先创建一个表-
create table DemoTable ( StudentFirstName varchar(20) );
使用插入命令在表中插入记录-
insert into DemoTable values('John'); insert into DemoTable values('Carol'); insert into DemoTable values('John'); insert into DemoTable values('John'); insert into DemoTable values('Bob'); insert into DemoTable values('David'); insert into DemoTable values('Bob'); insert into DemoTable values('Carol'); insert into DemoTable values('Robert');
使用select语句显示表中的所有记录-
select * from DemoTable;
这将产生以下输出-
+------------------+ | StudentFirstName | +------------------+ | John | | Carol | | John | | John | | Bob | | David | | Bob | | Carol | | Robert | +------------------+ 9 rows in set (0.00 sec)
这是计算MySQL中不同列的查询-
select StudentFirstName,count(*) from DemoTable group by StudentFirstName;
这将产生以下输出-
+------------------+----------+ | StudentFirstName | count(*) | +------------------+----------+ | John | 3 | | Carol | 2 | | Bob | 2 | | David | 1 | | Robert | 1 | +------------------+----------+ 5 rows in set (0.00 sec)