MySQL UPDATE append data into column

后端 未结 5 1303
后悔当初
后悔当初 2020-12-08 07:11

I need to UPDATE tablename (col1name)

If there is already data, I need to append it with values \'a,b,c\' If it is NULL, I need to add the values \'a,b,c\'

I

相关标签:
5条回答
  • 2020-12-08 07:54

    You can use the following:

    update yourtable 
    set yourcol = case when yourcol is null then 'a,b,c'
                      else concat(yourcol, ' a,b,c') end
    

    See SQL Fiddle with Demo

    Sample data:

    CREATE TABLE yourtable(`yourcol` varchar(50));
    
    INSERT INTO yourtable(`yourcol`)
    VALUES  ('sadsdh'),
        (NULL);
    

    Will return:

    |      YOURCOL |
    ----------------
    | sadsdh a,b,c |
    |        a,b,c |
    
    0 讨论(0)
  • 2020-12-08 07:57

    IFNULL(column,''), saves any if statements, makes the SQL much simpler!

    MySQL 5.6 Schema Setup:

    CREATE TABLE tablename
        (`yourcol` varchar(50))
    ;
    
    INSERT INTO tablename
        (`yourcol`)
    VALUES
        ('sadsdh'),
        (NULL)
    ;
    
    UPDATE tablename SET
        yourcol = CONCAT( IFNULL(yourcol,' '), 'somevalue' )
    ;
    

    Query:

    select *
    from tablename
    

    Results:

    |         yourcol |
    |-----------------|
    | sadsdhsomevalue |
    |       somevalue |
    
    0 讨论(0)
  • 2020-12-08 07:57

    why are you write ifnull function: it is obvious that if col1name1 is empty it concatenate to null means null+'a,b,c' simply 'a,b,c' set col1name = concat(ifnull(col1name,""), 'a,b,c') instead of this you can directly write set col1name = concat(col1name, 'a,b,c')

    0 讨论(0)
  • 2020-12-08 08:03

    Try this Query:

    update tablename set col1name = concat(ifnull(col1name,""), 'a,b,c');
    

    Refer this sql fiddle demo.

    0 讨论(0)
  • 2020-12-08 08:06

    This should do it:

    update tablename set
    col1name = if(col1name is null, 'a,b,c', concat(col1name, 'a,b,c'));
    


    Or you could make your life easier by doing it in two steps:

    update tablename set col1name = '' where col1name is null;
    

    then

    update tablename set col1name = concat(col1name, 'a,b,c');
    
    0 讨论(0)
提交回复
热议问题