Can't detect null value from JSON_EXTRACT

前端 未结 3 971
说谎
说谎 2020-12-11 15:10

I have a database that has an array of data stored in a JSON column. I need to find all values that have a null value at a particular position in the JSON array. While pulli

3条回答
  •  爱一瞬间的悲伤
    2020-12-11 15:51

    A bit of a belated answer but I just hit this problem and couldn't find anything reasonably documented. The solution I ended ended up using was the json_type function as 'abl' pointed out above.

    The trick was to compare with the string 'NULL' not null or NULL.

    As a test throw the following into a mysql prompt and play around with the values

    (if using phpMyAdmin don't forget to check 'show this query here again' and 'retain query box' - the universe is frustrating enough without losing edits..)

    set @a='{"a":3,"b":null}';
    
    select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
    

    I ended up with the following.

    mysql> set @a='{"a":3,"b":null}';
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
    +----------------------------------------------------+
    | if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0) |
    +----------------------------------------------------+
    |                                                  1 |
    +----------------------------------------------------+
    1 row in set (0.00 sec)
    
    mysql> set @a='{"a":3,"b":1}';
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> select if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0);
    +----------------------------------------------------+
    | if(json_type(json_extract(@a,'$.b')) = 'NULL',1,0) |
    +----------------------------------------------------+
    |                                                  0 |
    +----------------------------------------------------+
    1 row in set (0.00 sec)
    

    As the bare bones of a stored procedure - which is what I needed it for - using the 'if' statements rather than the if() function.

    drop procedure if exists test;
    delimiter $$
    
    create procedure test(in x json)
    begin
    
    if json_type(json_extract(x,'$.b')) = 'NULL' then
      select 1;
    else 
      select 0;
    end if;
    
    end$$
    
    delimiter;
    
    mysql> call test('{"a":3,"b":1}');
    +---+
    | 0 |
    +---+
    | 0 |
    +---+
    1 row in set (0.00 sec)
    
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> call test('{"a":3,"b":null}');
    +---+
    | 1 |
    +---+
    | 1 |
    +---+
    1 row in set (0.00 sec)
    
    Query OK, 0 rows affected (0.00 sec)
    

提交回复
热议问题