Update or Insert mysql column

868 views Asked by At

I have simple mySql question similar to SO "Update mysql column" I have a table table1 with at least two columns columns and a bunch of rows: [key_col|col_a|col_other] I want to update one column col_a if key_col=number exist or insert if not exists. I first must do select or update do insert automatically?

2

There are 2 answers

4
prashant On

if key_col is a primary key then do a replace into instead of doing insert into.....replace into will insert if the key does not exist else update if the key exists.

0
Crouching Kitten On

See this answer: Insert into a MySQL table or update if exists

What you said: "I want to update if key exists or insert if not exists" is equivalent to the opposite order: "insert if not exists or update if exists", because the 2 cases are mutually exclusive.

First make sure that key_col has a unique index (like: primary key). Then this would work:

insert into
    `table1`
    (`key_col`, `col_a`, ...)
values
    (123, 234, ...)
on duplicate key update
    `col_a` = 234, ...;

At "..." place the other fields.