MYSQL update if not exists else do nothing -
my question how update value in table if not exists on table.i checked insert ... on duplicate key update describes inserting updates , not insert.
my situation like, have 2 tables (t1,t2). want update column in t1 value if not present in t2. otherwise increment value , try update again. want like
update t1 set column = 'value' if not exists in t2
can suggest solution
here way using join.
create table tab1 (id int , val int); insert tab1 values (1,1),(2,3),(3,5); create table tab2 (id int , val int); insert tab2 values (4,1),(2,3),(3,5);
in above tab1 (id = 1) not available in tab2 , using following command can update such values
update tab1 t1 left join tab2 t2 on t1.id = t2.id set t1.val = case when t2.id null 8 else t1.val end
the output after update command like
mysql> select * tab1 ; +------+------+ | id | val | +------+------+ | 1 | 8 | | 2 | 3 | | 3 | 5 | +------+------+
also can use exist pretty better doing left join
update tab1 t1 set t1.val = 10 not exists ( select 1 tab2 tab2.id = t1.id )
Comments
Post a Comment