I want to perform some updates to posts’ meta data in a WordPress site (wp_postmeta table).
The known good’ol function update_post_meta() is doing the job and also will check and if key not exist, it will add it.
But, this function can handle only one post at a time.
I want to save expensive db calls and update with one query several fields for different post ids.
Generally, I could use mySQL UPDATE query with CASE to swich and assign each meta_value according to post_id, like in this example, and update some values of different rows in the table.
But, it may be that for some of the posts, that meta_key is not existing yet, so INSERT is needed and not update. Well, if not using the update_post_meta(), I should check this somehow.
I tried to use INSERT .... ON DUPLICATE UPDATE (syntax) and also REPLACE (syntax), but it is relevant only for columns that are unique or defined as primary keys, so it doesn’t help in this case.
Is there a way or an idea for how can I have the “Insert value, and update if already exists this meta_key for this post_id” and do this for several different post_ids (same meta_key however all the way), and with one single mySQL query?
Thanks
(* I asked this also in WordPress answers, and asking here too)
REPLACEandINSERT ... ON DUPLICATE KEY UPDATEare not “relevant only for columns that are unique or defined as primary keys”, rather the determination of whether the record is new or already existing (and thus needs to be replaced/updated) is made on whether there is a unique key collision or not. As the MySQL documentation states:It describes
INSERT ... ON DUPLICATE KEY UPDATEsimilarly.Therefore, provided your
REPLACEorINSERT ... ON DUPLICATE KEY UPDATEcommand identifies your updated records by their current primary keys, it should do exactly what you wish. According to the WordPress documentation, the primary key is themeta_idfield, so with aSELECTyou obtain this identifier for the existing cases and with an outer join, getNULLif it doesn’t already exist (which sets the column to the nextauto_incrementvalue):If the new meta value is to be different for each post, you could add such values as a second column in
temp_table: