MySQL 数据库中所有行的精确计数?
要精确统计所有行,您需要使用聚合函数 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;
以下是带有行计数的输出 −
+-------------------+ | TotalNumberOfRows | +-------------------+ | 9 | +-------------------+ 1 row in set (0.00 sec)
广告