How to implement this mysql query? -
insert table if duplicate exits select row primary key else insert table , return last insert id ?
select if (exists(select * users username='adminchat')) begin select userid users username='adminchat'; end; else begin insert `users`( `userrole`, `username`, `createdon`, `emailid`, `is_active`, `password`) values (1,'user1_chat',now(),'sdmd1@sdmd1.com',1,'123456') select last_insert_id(); end;
if table contains auto_increment column , insert ... update inserts row, last_insert_id() function returns auto_increment value. if statement updates row instead, last_insert_id() not meaningful. however, can work around using last_insert_id(expr). suppose id auto_increment column. make last_insert_id() meaningful updates, insert rows follows:
insert table (a,b,c) values (1,2,3) on duplicate key update id=last_insert_id(id), c=3;
a way make things work use dummy column, if have table auto_increment column id , unique key a,b , smallint dummy column instance, query might this:
insert test (a,b) values ('1','2') on duplicate key update id=last_insert_id(id),dummy = not dummy; now, select last_insert_id(); return correct id.
Comments
Post a Comment