为此,您可以COUNT()使用不包含 NULL 值的方法。让我们首先创建一个表 -
mysql> create table DemoTable -> ( -> Name varchar(100), -> CountryName varchar(100) -> );
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable values('John',null); mysql> insert into DemoTable values('Chris','US'); mysql> insert into DemoTable values('Robert',null); mysql> insert into DemoTable values('Bob','UK');
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;输出结果
这将产生以下输出 -
+--------+-------------+ | Name | CountryName | +--------+-------------+ | John | NULL | | Chris | US | | Robert | NULL | | Bob | UK | +--------+-------------+ 4 rows in set (0.00 sec)
这是要使用COUNT()和忽略 NULL的查询-
mysql> select count(Name) AS TotalName,count(CountryName) AS CountryWhichIsNotNull from DemoTable;输出结果
这将产生以下输出 -
+-----------+-----------------------+ | TotalName | CountryWhichIsNotNull | +-----------+-----------------------+ | 4 | 2 | +-----------+-----------------------+ 1 row in set (0.00 sec)