Computer >> Máy Tính >  >> Lập trình >> MySQL

Số lượng chính xác của tất cả các hàng trong cơ sở dữ liệu MySQL?

Để đếm chính xác tất cả các hàng, bạn cần sử dụng hàm tổng hợp COUNT (*). Cú pháp như sau -

select count(*) as anyAliasName from yourTableName;

Để hiểu cú pháp trên, chúng ta hãy tạo một bảng. Truy vấn để tạo bảng như sau -

mysql> create table CountAllRowsDemo
   -> (
   -> Id int,
   -> Name varchar(10),
   -> Age int
   -> );
Query OK, 0 rows affected (1.49 sec)

Bây giờ bạn có thể chèn một số bản ghi trong bảng bằng cách sử dụng lệnh insert. Truy vấn như sau -

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)

Hiển thị tất cả các bản ghi từ bảng bằng cách sử dụng một câu lệnh chọn. Truy vấn như sau -

mysql> select *from CountAllRowsDemo;

Sau đây là kết quả -

+------+-------+------+
| 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)

Đây là cách bạn có thể đếm số hàng chính xác trong bảng bằng cách sử dụng hàm tổng hợp (*).

Truy vấn như sau -

mysql> select count(*) as TotalNumberOfRows from CountAllRowsDemo;

Sau đây là kết quả với số lượng hàng -

+-------------------+
| TotalNumberOfRows |
+-------------------+
|                 9 |
+-------------------+
1 row in set (0.00 sec)