如何在 MySQL 中计算不同的列?
mysqlmysqli database更新于 2025/9/13 21:32:17
您需要使用 GROUP BY 来实现这一点。让我们首先创建一个表 −
mysql> create table DemoTable ( StudentFirstName varchar(20) ); Query OK, 0 rows affected (0.74 sec)
使用 insert 命令在表中插入记录 −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (1.34 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable;
这将产生以下输出 −
+------------------+ | StudentFirstName | +------------------+ | John | | Carol | | John | | John | | Bob | | David | | Bob | | Carol | | Robert | +------------------+ 9 rows in set (0.00 sec)
这是在 MySQL 中计算不同列的查询 −
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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

