lundi 13 juin 2016

mySQL Statement: How to INSERT .... UPDATE a record-set without a PRI or UNIQUE key

I know it's another UPDATE record if already exists otherwise INSERT type of question but I looked at almost all the related post but couldn't figure out. I'm running a bash script to make an entry in the WordPress wp_sitemeta table to configure Duo Security plugin. This is the table structure:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| meta_id    | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| site_id    | bigint(20)   | NO   | MUL | 0       |                |
| meta_key   | varchar(255) | YES  | MUL | NULL    |                |
| meta_value | longtext     | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

The issue is: None of the field I'm inserting the data for neither primary or unique and I want to prevent the duplicate inserts but I also want to update the data-set if meta_value changes in that particular row. I'm using this at the moment:

INSERT INTO wp_sitemeta (site_id, meta_key, meta_value) 
SELECT '1', 'duo_role', 'a:2:{s:13:"administrator";s:6:"editor";}' 
FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM wp_sitemeta 
WHERE site_id='1' AND meta_key='duo_role' 
AND meta_value='a:2:{s:13:"administrator";s:6:"editor";}' LIMIT 1 );

which prevents the duplicate entries nicely if meta_value didn't change but doesn't really help if meta_value changed. I also tried with INSERT ... ON DUPLICATE KEY UPDATE but no joy yet. Can anyone help me on this please?

Aucun commentaire:

Enregistrer un commentaire