Let say I have a MySQL table which contains three columns: id
, a
and b
and the column named id
is an AUTO INCREMENT
field. If I pass a query like the following to MySQL, it will works fine:
REPLACE INTO `table` (`id`, `a`, `b`) VALUES (1, 'A', 'B')
But if I skip the field id
it will no longer works, which is expected.
I want to know if there is a way to ignore
some fields in the REPLACE
query. So the above query could be something like this:
REPLACE INTO `table` (`a`, `b`) VALUES ('A', 'B')
Why do I need such a thing?
Sometimes I need to check a database with a SELECT
query to see if a row exists or not. If it is exists then I need to UPDATE
the existing row, otherwise I need to INSERT
a new row. I'm wondering if I could achieve a similar result (but not same) with a single REPLACE
query.
Why it couldn't be the same result? Simply because REPLACE
will DELETE
the existing row and will INSERT
a new row, which will lose the current primary key
and will increase the auto incremented values. In contrast, in an UPDATE
query, primary key
and the AI
fields will be untouched.
MySQL REPLACE.