Listing both null and not null in mysql query

2019-04-09 17:34发布

问题:

Let's say I have the table

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

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

I could run these two queries

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

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

回答1:

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) is equivalent to COUNT(*), so it will really make a count.



回答2:

If it is ok with a solution that uses grouping you can try something like:

SELECT ISNULL(ref),COUNT(*) FROM TABLE GROUP BY ISNULL(ref)

At least it tells you how many row with a NULL in ref you have. This solution (good or not) could be extended with a select of GROUP_CONCAT on NAME if you need to select every individual name.



回答3:

I think MySQL has an IF() function, so you could write:

SELECT Name, SUM(IF(ISNULL(Ref), 1, 0)) AS NullCount,
       SUM(IF(ISNULL(Ref), 0, 1)) AS NotNullCount
FROM Table GROUP BY Name

So, you're using the IF() function to generate either a zero or a one for each row, and summing them to get the total number of "ones".



标签: mysql null