如何计算 MySQL 中的 NULL 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3057746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:21:42  来源:igfitidea点击:

How to count NULL values in MySQL?

mysqlaggregate-functions

提问by abbr

I want to know how can i find all the values that are NULL in the MySQL database for example I'm trying to display all the users who don't have an average yet.

我想知道如何在 MySQL 数据库中找到所有为 NULL 的值,例如我试图显示所有还没有平均值的用户。

Here is the MySQL code.

这是 MySQL 代码。

SELECT COUNT(average) as num
FROM users
WHERE user_id = '$user_id'
AND average IS_NULL

采纳答案by Hammerite

SELECT
    COUNT(*) as num
FROM
    users
WHERE
    user_id = '$user_id' AND
    average IS NULL

回答by ircmaxell

A more generic version (that doesn't depend on the where clause and hence limits your overall results):

更通用的版本(不依赖于 where 子句,因此会限制您的整体结果):

SELECT 
    SUM(CASE WHEN average IS NULL THEN 1 ELSE 0 END) As null_num, 
    SUM(CASE WHEN average IS NOT NULL THEN 1 ELSE 0 END) AS not_null_num
FROM users

It's not better then the specific queries presented by other answers here, but it can be used in situations where using a limiting where clause is impractical (due to other information being needed)...

它并不比此处其他答案提供的特定查询更好,但可以在使用限制 where 子句不切实际的情况下使用(由于需要其他信息)...

回答by Charles Bretana

Also, you can:

此外,您还可以:

Select Count(*) - Count(Average) as NullAverages
From Users
Where user_id = '$user_id' 

回答by Jacob

you're on the right track. Remove '_' from 'IS_NULL' and change 'COUNT(average)' to 'COUNT(1)' and you will have it.

你在正确的轨道上。从“IS_NULL”中删除“_”并将“COUNT(average)”更改为“COUNT(1)”,您将拥有它。

For more information on working with NULL in MYSQL see http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

有关在 MYSQL 中使用 NULL 的更多信息,请参阅http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

And for working with IS NULL specifically see

对于使用 IS NULL 的工作,请特别参阅

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_is-null

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_is-null

回答by μBio

I may be missing something mysql specific but this would work in sql server

我可能会遗漏一些特定于 mysql 的东西,但这可以在 sql server 中使用

SELECT COUNT(*) as num
FROM users
WHERE user_id = '$user_id'
AND average IS NULL

回答by ATorras

A bit late but you can do it in MySQL 5.0.51:

有点晚了,但你可以在 MySQL 5.0.51 中做到:

SELECT COUNT(*) AS total, COUNT(field1) AS notNullFields1
FROM table
GROUP BY field5, field6

Regards.

问候。

回答by Prozac

This is a one liner that also could be used for this problem :

这是一个也可用于解决此问题的单衬:

SELECT COUNT(IF(average IS NULL,1,0))
FROM table; 

It worked like a charm for me!

它对我来说就像一个魅力!