简体   繁体   English

计算每行mysql的Null变量数

[英]count number of Null variables per row mysql

We have the following table in Mysql using innoDB: 我们在MySQL中使用innoDB的下表如下:

id   Var1   Var2  Var 3     
1    NULL    1     2   
2    2    NULL    NULL  
3    4       2    NULL 

We pretend to produce Var4 with the number of NULL variables per row: 我们假装产生的Var4每行具有NULL变量数:

id Var4  
1    1  
2    2  
3    1 

I tried unsuccessfully : 我尝试失败:

update db.table 
set var4 = ISNULL(var1) + ISNULL(var2) + ISNULL(var3);

any suggestions? 有什么建议么?

Here is one way: 这是一种方法:

select id, ((var1 is null) + (var2 is null) + (var3 is null)) as var4
from table t;

MySQL treats booleans as integers, with true being 1 and false being 0 . MySQL将布尔值视为整数,true为1 ,false为0 You can just add them up to get the total. 您可以将它们加起来以获得总数。

As an update: 作为更新:

update table t
    set var4 = ((var1 is null) + (var2 is null) + (var3 is null));

As a note, MySQL doesn't support ISNULL() . 注意,MySQL不支持ISNULL() That is more of a SQL Server function. 那更多的是SQL Server功能。 But it is not ANSI standard anyway, so you are usually better off using coalesce() . 但这不是ANSI标准,因此通常最好使用coalesce()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM