How to count NULL values in MySQL?

一曲冷凌霜 提交于 2019-12-03 08:52:24

问题


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.

Here is the MySQL code.

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

回答1:


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



回答2:


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

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




回答3:


Also, you can:

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



回答4:


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

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

And for working with IS NULL specifically see

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




回答5:


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

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



回答6:


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

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

Regards.




回答7:


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!



来源:https://stackoverflow.com/questions/3057746/how-to-count-null-values-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!