I need to write an SQL query for MySQL so that a row is updated if it exists, but inserted if it does not.
i.e.
If row exists...
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
If it does not exist...
INSERT INTO Table1 VALUES (...)
Can this be done in one query?
i believe you need to reverse your logic in order for it to work:
insert into a table - if it exists (same key) then update it.
this can be achieved by the ON DUPLICATE
statement like so:
INSERT INTO Table1 VALUES(...)
ON DUPLICATE KEY UPDATE column=column+1
check the manual here
Use the INSERT... ON DUPLICATE KEY UPDATE
syntax.
See the manual
(For searching purposes, btw, this is usually referred to as an "upsert")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With