为什么我的NULL计数在MySQL中返回0?非常基本的

时间:2012-10-13 20:48:13

标签: mysql

我有两个让我困惑的简单问题(我是Mysql的新手)

我有一个包含3列的表(调查),UserID(主要),SkinColor和HairColor。我想计算头发颜色为空的人数(他们没有回答调查)。

我是这样做的:

select count(id)
from survey
where haircolor is null

但我很疑惑为什么我不能做

select count(haircolor)
from survey
where haircolor is null

它返回0.这是为什么?

问题2:我想返回调查受访者的总数(所有ID),头发颜色为空值的人数和肤色的空值。我试过这个查询

select count(id), count(skincolor), count(haircolor)
from survey
where skincolor is null and haircolor is null

但是,这只是返回了skincolor和haircolor明显为空的计数,而不是每列的单独计数。有没有办法将WHERE约束放在SELECT部分​​中,这样我可以为每个选择指定不同的约束?

谢谢!

3 个答案:

答案 0 :(得分:2)

我是这样做的:

  

选择计数(id)   来自调查   haircolor为null的地方

但我很疑惑为什么我不能做

  

选择计数(发色)   来自调查   haircolor为null的地方

它第一次起作用,因为第一次计算ID为X时,其中X为空,而IS本身不为空。第二次计算自身为NULL的事物和NULL事物的COUNT为0。

答案 1 :(得分:0)

关于问题2:

这很容易,因为COUNT(null)为0:

 select count(id), count(skincolor), count(haircolor) from survey

这为您提供了每列的非空值数。

您还应该能够做到以下几点:

SELECT count(1) AS num, 
       count(1)-count(skincolor) AS nullcolor, 
       count(1)-count(haircolor) AS nullhair 
    FROM survey

答案 2 :(得分:0)

第二种情况:

select 'No haircolor', count(id)
from survey
where haircolor is null
union all 
select 'no skincolor',count(id)
from survey
where skincolor is null

这应该返回类似:

No haircolor   3
No skincolor   1

如果您希望将结果作为一行,则需要对上述结果进行调整。

注意:我假设字符串文字引用单引号,如MsSql