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)
廣告