计算 MySQL 中 NOT NULL 值的存在
要计算NOTNULL值的存在,请使用聚合函数COUNT(yourColumnName)。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, NumberOfQuestion int, NumberOfSolution int );
使用插入命令在表中插入一些记录。在这里,一些值是NULL-
mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,10); mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,2); mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,NULL); mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,NULL); mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(30,19); mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(30,1);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+------------------+------------------+ | Id | NumberOfQuestion | NumberOfSolution | +----+------------------+------------------+ | 1 | 20 | 10 | | 2 | 20 | 2 | | 3 | 20 | NULL | | 4 | 20 | NULL | | 5 | 30 | 19 | | 6 | 30 | 1 | +----+------------------+------------------+ 6 rows in set (0.00 sec)
以下是计算值存在的查询。相同的值应该不是NULL,即不会计算NULL值-
mysql> SELECT NumberOfQuestion, COUNT(NumberOfSolution) as NumberOfRows FROM DemoTable GROUP BY NumberOfQuestion;
这将产生以下输出-
+------------------+--------------+ | NumberOfQuestion | NumberOfRows | +------------------+--------------+ | 20 | 2 | | 30 | 2 | +------------------+--------------+ 2 rows in set (0.00 sec)