Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Truy vấn MySQL đếm giá trị cột từ hai cột và loại trừ NULL


Tạo bảng mẫu:

mysql> create table DemoTable1975 ( StudentName varchar(20), StudentMarks int ); Query OK, 0 rows affected (0.00 sec)

Thêm dữ liệu:

mysql> insert into DemoTable1975 values('John',45); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1975 values('Chris',67); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1975 values('David',59); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1975 values('Bob',NULL); Query OK, 1 row affected (0.00 sec)

Hiển thị dữ liệu:

mysql> select * from DemoTable1975;
+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| John        | 45           |
| Chris       | 67           |
| David       | 59           |
| Bob         | NULL         |
+-------------+--------------+
4 rows in set (0.00 sec)

Truy vấn đếm giá trị không NULL của hai cột:

mysql> select count(StudentName)+count(StudentMarks) from DemoTable1975;

Kết quả (count bỏ qua NULL):

+----------------------------------------+
| count(StudentName)+count(StudentMarks) |
+----------------------------------------+
| 7                                      |
+----------------------------------------+
1 row in set (0.00 sec)