How to update column with null value

前端 未结 13 637
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 05:08

I am using mysql and need to update a column with a null value. I have tried this many different ways and the best I have gotten is an empty string.

Is there a speci

相关标签:
13条回答
  • 2020-12-13 05:42

    Remember to look if your column can be null. You can do that using

    mysql> desc my_table;
    

    If your column cannot be null, when you set the value to null it will be the cast value to it.

    Here a example

    mysql> create table example ( age int not null, name varchar(100) not null );
    mysql> insert into example values ( null, "without num" ), ( 2 , null );
    mysql> select * from example;
    +-----+-------------+
    | age | name        |
    +-----+-------------+
    |   0 | without num |
    |   2 |             |
    +-----+-------------+
    2 rows in set (0.00 sec)
    
    mysql> select * from example where age is null or name is null;
    Empty set (0.00 sec)
    
    0 讨论(0)
  • 2020-12-13 05:44

    NULL is a special value in SQL. So to null a property, do this:

    UPDATE table SET column = NULL;
    
    0 讨论(0)
  • 2020-12-13 05:44

    In the above answers, many ways and repetitions have been suggested for the same. I kept looking for an answer as mentioned is the question but couldn't find here.

    Another way to put the above question "update a column with a null value" could be "UPDATE ALL THE ROWS IN THE COLUMN TO NULL"

    In such a situation following works

    update table_name
    set field_name = NULL
    where field_name is not NULL;
    

    is as well is not works in mysql

    0 讨论(0)
  • 2020-12-13 05:47

    Use IS instead of = This will solve your problem example syntax:

    UPDATE studentdetails
    SET contactnumber = 9098979690
    WHERE contactnumber IS NULL;
    
    0 讨论(0)
  • 2020-12-13 05:47

    On insert we can use

    $arrEntity=$entity->toArray();        
        foreach ($arrEntity as $key => $value) {    
            if (trim($entity->$key) == '' && !is_null($entity->$key) && !is_bool($entity->$key)){
            unset($entity->$key);
            }
        }
    

    On update we can use

    $fields=array();
    foreach ($fields as $key => $value) {
            if (trim($value) == '' && !is_null($value) && !is_bool($value)){
                $fields[$key] = null;
            }
        }
    
    0 讨论(0)
  • 2020-12-13 05:50

    No special syntax:

    CREATE TABLE your_table (some_id int, your_column varchar(100));
    
    INSERT INTO your_table VALUES (1, 'Hello');
    
    UPDATE your_table
    SET    your_column = NULL
    WHERE  some_id = 1;
    
    SELECT * FROM your_table WHERE your_column IS NULL;
    +---------+-------------+
    | some_id | your_column |
    +---------+-------------+
    |       1 | NULL        |
    +---------+-------------+
    1 row in set (0.00 sec)
    
    0 讨论(0)
提交回复
热议问题