MySQL INSERT else if exists UPDATE

2019-04-02 07:57发布

问题:

I'm building a config table with two columns, config_name and config_value. I insert multiple rows in one statement:

INSERT INTO ".$dbPrefix."config (config_name,config_value) VALUES
             ('domain','$domain'),
             ('forest_root','$fr_if'),
             ('userGroup','$userGroup'),
             ('adminGroup','$adminGroup');

The config_name column is a primary key. How would I change this statement to automatically update the config_value if the config_name already exists?

回答1:

You could try this syntax:

INSERT INTO table (field) VALUES (value) ON DUPLICATE KEY UPDATE field=value

Docs can be found here.



回答2:

You're trying to do an upsert, and I think this may help: http://database-programmer.blogspot.com/2009/06/approaches-to-upsert.html



标签: php mysql insert