Update multiple columns in MySQL but only when a value is not null -
i have mysql table multiple columns, a, b, , c.
i update columns using 1 sql statement. however, of columns can null.
so, if null, update b , c.
if , b null, update c.
and on, other combinations.
how can in 1 single statement?
thanks.
you can use if within update clause:
update test_update set a=if(a null, null, 'a2'), b=if(b null, null, 'b2'), c=if(c null, null, 'c2');
example run:
mariadb [test]> select * test_update; +------+------+------+ | | b | c | +------+------+------+ | a1 | null | null | | null | b1 | null | | null | null | c1 | | a1 | b1 | null | | a1 | null | c1 | | null | b1 | c1 | | a1 | b1 | c1 | +------+------+------+ 7 rows in set (0.00 sec) mariadb [test]> update test_update set a=if(a null, null, 'a2'), b=if(b null, null, 'b2'), c=if(c null, null, 'c2'); query ok, 7 rows affected (0.00 sec) rows matched: 7 changed: 7 warnings: 0 mariadb [test]> select * test_update; +------+------+------+ | | b | c | +------+------+------+ | a2 | null | null | | null | b2 | null | | null | null | c2 | | a2 | b2 | null | | a2 | null | c2 | | null | b2 | c2 | | a2 | b2 | c2 | +------+------+------+ 7 rows in set (0.00 sec)
Comments
Post a Comment