count number of Null variables per row mysql

后端 未结 1 1008
粉色の甜心
粉色の甜心 2020-12-22 08:50

We have the following table in Mysql using innoDB:

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


        
相关标签:
1条回答
  • 2020-12-22 09:36

    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. 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(). That is more of a SQL Server function. But it is not ANSI standard anyway, so you are usually better off using coalesce().

    0 讨论(0)
提交回复
热议问题