精确计算 MySQL 数据库中的所有行数?
mysqlmysqli database
要精确计算所有行数,您需要使用聚合函数 COUNT(*)。语法如下 −
select count(*) as anyAliasName from yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table CountAllRowsDemo -> ( -> Id int, -> Name varchar(10), -> Age int -> ); Query OK, 0 rows affected (1.49 sec)
现在,您可以使用 insert 命令在表中插入一些记录。查询如下 −
mysql> insert into CountAllRowsDemo values(1,'John',23); Query OK, 1 row affected (0.15 sec) mysql> insert into CountAllRowsDemo values(101,'Carol',21); Query OK, 1 row affected (0.17 sec) mysql> insert into CountAllRowsDemo values(201,'Sam',24); Query OK, 1 row affected (0.13 sec) mysql> insert into CountAllRowsDemo values(106,'Mike',26); Query OK, 1 row affected (0.22 sec) mysql> insert into CountAllRowsDemo values(290,'Bob',25); Query OK, 1 row affected (0.16 sec) mysql> insert into CountAllRowsDemo values(500,'David',27); Query OK, 1 row affected (0.16 sec) mysql> insert into CountAllRowsDemo values(500,'David',27); Query OK, 1 row affected (0.19 sec) mysql> insert into CountAllRowsDemo values(NULL,NULL,NULL); Query OK, 1 row affected (0.23 sec) mysql> insert into CountAllRowsDemo values(NULL,NULL,NULL); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from CountAllRowsDemo;
以下是输出 −
+------+-------+------+ | Id | Name | Age | +------+-------+------+ | 1 | John | 23 | | 101 | Carol | 21 | | 201 | Sam | 24 | | 106 | Mike | 26 | | 290 | Bob | 25 | | 500 | David | 27 | | 500 | David | 27 | | NULL | NULL | NULL | | NULL | NULL | NULL | +------+-------+------+ 9 rows in set (0.00 sec)
下面介绍如何使用聚合函数 count(*) 计算表中的确切行数。
查询如下 −
mysql> select count(*) as TotalNumberOfRows from CountAllRowsDemo;
The following is the output with the count of rows −
+-------------------+ | TotalNumberOfRows | +-------------------+ | 9 | +-------------------+ 1 row in set (0.00 sec)