I have table foo
with PK int id
,varchar state
table foo:
- int id
- varchar state
- int code1
- int code2
I want to do an sql insert if the record not already exist.
To complete the insert statement, I have to retrieve some info with an insert select.
In input I have:
id = 1, state = 'A'
In the insert I have to fill the other field with values retrieved with insert select.
code1 and code2 where id = 1 (they are always the same for id = x)
Normally I have to do:
1- a select with where id=1 and state=1
, and if not exist I will have to do the sql insert
2- if record not exist retrieve the values of fields code1 and code2 when id=1
3- do the insert
Is it possible to do all in one query?
select * from foo where id=1 and state = 'A'
if not exist already:
select code1,code2 from foo where id=1; #1,2
insert into foo(id, state, code1, code2) values (1,'A', 1, 2);
is it possible to merge in one query?
Thanks