mysql - insert when a particular record not found -
mysql - insert when a particular record not found -
i got situation need insert if record not exist. normally, i'm going utilize 2 queries conditions this:
select table -> if record not found -> insert table else -> nil
i sense solution not one. how can accomplish same thing single query? example:
select * user status='a' , name='lewis' if record not found insert user(status,name) values('f','lewis');
you mean like:
begin if not exists (select * user status='a' , name='lewis') begin insert user (status, name) values('f','lewis') end end
this works in sql server, , should possible in mysql well.
edit:
apparently it's not working in mysql (just testd). however, utilize insert ignore
:
insert ignore user2 (status, name) values('f','lewis');
note that work if have unique or primary key.
another way have same unique or primary key, , use:
insert ignore user2 (status, name) values('f','lewis') on duplicate key update status=status;
this avoids ending other errors beingness ignored, , ignores duplicate key warning.
mysql sql
Comments
Post a Comment