如何檢查 MySQL 資料庫表中有多少行?


要了解 ySQL 資料庫表中有多少行,你需要使用聚合函式 COUNT(*)。

語法如下

SELECT COUNT(*) FROM yourTableName;

為了瞭解以上語法,我們來建立一個表。建立表的查詢如下

mysql> create table CountRowsDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Name varchar(20)
   - > );
Query OK, 0 rows affected (0.78 sec)

使用 insert 命令向表中插入一些記錄。

查詢如下

mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into CountRowsDemo(Name) values('Sam');
Query OK, 1 row affected (0.25 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values('Mike');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountRowsDemo(Name) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.09 sec)
mysql> insert into CountRowsDemo(Name) values('Carol');
Query OK, 1 row affected (0.17 sec)

使用 select 語句從表中顯示所有記錄。

查詢如下

mysql> select *from CountRowsDemo;

以下為輸出

+----+-------+
| Id | Name  |
+----+-------+
|  1 | NULL  |
|  2 | Sam   |
|  3 | NULL  |
|  4 | Mike  |
|  5 | David |
|  6 | NULL  |
|  7 | NULL  |
|  8 | Carol |
+----+-------+
8 rows in set (0.00 sec)

現在,讓我們執行以下查詢來對錶中的行進行計數

mysql> select count(*) AS TotalRows from CountRowsDemo;

以下為輸出

+-----------+
| TotalRows |
+-----------+
|         8 |
+-----------+
1 row in set (0.00 sec)

更新於: 30-Jul-2019

1K+ 瀏覽次數

開啟 職業生涯

完成課程,獲得認證

開始
廣告