在mysql查询中同时列出null和not null [英] Listing both null and not null in mysql query

查看:87
本文介绍了在mysql查询中同时列出null和not null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有桌子

NAME | ID | REF  
foo1 | 1 | NULL  
foo2 | 2 | 1234  
foo2 | 3 | 567  
foo1 | 4 | NULL  
foo3 | 5 | 89  

我想在一个查询中计算NULL和NOT NULL的所有实例,以便我能说

I'd like to count all instances of NULL and NOT NULL in one query so that I can say

NAME | null | not null  
foo1 |  0   |   2  
foo2 |  2   |   0  
foo3 |  0   |   1

我可以运行这两个查询

select NAME,count(*) from TABLE where REF is not null  
select NAME,count(*) from TABLE where REF is null

但是我敢肯定,在一个mysql查询中必须有一种简单的方法.

But I'm sure there must be a simple way to do it in one mysql query.

推荐答案

您可以像这样在ISNULL()上使用SUM()

You can use SUM() on ISNULL() like this

select NAME, sum(isnull(REF)) as is_null, sum(not isnull(REF)) as is_not_null from TABLE group by NAME;

SUM(1)等同于COUNT(*),因此它确实可以计数.

SUM(1) is equivalent to COUNT(*), so it will really make a count.

这篇关于在mysql查询中同时列出null和not null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆