mysql - SQL Insert into table only if record doesn't exist -
this question has answer here:
- check if row exists, otherwise insert 10 answers
- mysql conditional insert 11 answers
i want run set of queries insert data sql table if record satisfying criteria met. table has 4 fields: id
(primary), fund_id
, date
, price
i have 3 fields in query: fund_id
, date
, price
.
so query go this:
insert funds (fund_id, date, price) values (23, '2013-02-12', 22.43) not exists ( select * funds fund_id = 23 , date = '2013-02-12' );
so want insert data if record matching fund_id
, date
not exist. if above correct strikes me quite inefficient way of achieving additional select statement must run each time.
is there better way of achieving above?
edit: clarification neither fund_id
nor date
unique fields; records sharing same fund_id or date exist no record should have both same fund_id , date another.
this might simple solution achieve this:
insert funds (id, date, price) select 23, date('2013-02-12'), 22.5 dual not exists (select 1 funds id = 23 , date = date('2013-02-12'));
p.s. alternatively (if id
primary key):
insert funds (id, date, price) values (23, date('2013-02-12'), 22.5) on duplicate key update id = 23; -- or whatever need
see this fiddle.
Comments
Post a Comment