Reputation: 3
I want to insert new rows into a mysql table, but when same row already exists then update rows. So for example
`INSERT INTO table (character_id, data) VALUES(1212, "test")` WHEN character_id exist then UPDATE...
Any one know how to create sql query for this?
Upvotes: 0
Views: 66
Reputation: 2273
You can use the following query to do this:
IF EXISTS (select * from demo where character_id=1212)
update demo
set character_id=123 and data='test'
where id=1212
ELSE
insert into demo (character_id, data)
values(1212, "test");
More efficient way of doing this would be as suggested by juergen d in comment:
INSERT INTO demo (character_id, data)
VALUES(1212, "test")
ON DUPLICATE KEY UPDATE character_id=123 ,data='test'
For Reference: MySQL Documentation-Insert-on-duplicate
Upvotes: 3