MySQL数据库中所有行的确切计数?

要精确计数所有行,您需要使用聚合函数COUNT(*)。语法如下-

select count(*) as anyAliasName from yourTableName;

为了理解上述语法,让我们创建一个表。创建表的查询如下-

mysql> create table CountAllRowsDemo
   -> (
   -> Id int,
   -> Name varchar(10),
   -> Age int
   -> );

现在,您可以使用insert命令在表中插入一些记录。查询如下-

mysql> insert into CountAllRowsDemo values(1,'John',23);
mysql> insert into CountAllRowsDemo values(101,'Carol',21);
mysql> insert into CountAllRowsDemo values(201,'Sam',24);
mysql> insert into CountAllRowsDemo values(106,'Mike',26);
mysql> insert into CountAllRowsDemo values(290,'Bob',25);
mysql> insert into CountAllRowsDemo values(500,'David',27);
mysql> insert into CountAllRowsDemo values(500,'David',27);
mysql> insert into CountAllRowsDemo values(NULL,NULL,NULL);
mysql> insert into CountAllRowsDemo values(NULL,NULL,NULL);

使用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)