mysql - If data exists UPDATE else INSERT SQL query - No foreign key -
i have problem, want make 1 query update if field exists, , insert new 1 if not. problem id not unique, cant use on duplicate key update
i tried if exists solution
if exists (select * wordpress.wp_4_postmeta post_id=3466 , meta_key='_job_expires') update wp_4_postmeta set meta_value='2017-06-25' post_id=3466 , meta_key='_job_expires' else insert wordpress.wp_4_postmeta (post_id,meta_key,meta_value) values (3466,'_job_expires','2017-09-25')
and tried rowcount
update wordpress.wp_4_postmeta set meta_value='01-01-2685' post_id=3471 if @@rowcount = 0 insert wordpress.wp_4_postmeta (post_id,meta_key,meta_value) values (3471,'_job_expires','2017-09-25')
but no luck. how can in 1 query?
i'm additionally attaching pictures of database table, see going on. post_id not unique, there can lot of same post_id different meta_key-s.
this tried, on duplicate key
no luck
insert wordpress.wp_4_postmeta (post_id, meta_key, meta_value) values (3466, '_job_expires', '2011-06-25') on duplicate key update meta_value='2011-06-25';
the proper solution on duplicate key update
.
first, need unique key post_id, meta_key
:
create unique index unq_postmeta_post_metakey on wordpress.wp_4_postmeta(post_id, meta_key);
then can use on duplicate key update
:
insert wordpress.wp_4_postmeta (post_id, meta_key, meta_value) values (3466, '_job_expires', '2017-09-25') on duplicate key update meta_value='2017-06-25';
i note 2 dates different. intentional?
Comments
Post a Comment