MySQL INSERT else if exists UPDATE

2019-04-02 07:33发布

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?

标签: php mysql insert
2条回答
ゆ 、 Hurt°
2楼-- · 2019-04-02 08:16

You could try this syntax:

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

Docs can be found here.

查看更多
爷、活的狠高调
3楼-- · 2019-04-02 08:24

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

查看更多
登录 后发表回答