MySQL
Recommended:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE name="A", age=19
Pros:
- Easy to understand
- Won't change the ID, friendly with auto-increment keys or unique keys
- Efficient.
- Only changed values need to be provided
Cons:
- Long statement.
- Doesn't work for non-UNIQUE or PRIMARY keys.
Alternative:
REPLACE into table (id, name, age) values(1, "A", 19)
Cite:http://dev.mysql.com/doc/refman/5.0/en/replace.html
Pros:
- Shorter statement, easy to understand.
- Works for all cases.
Cons:
- It's actually a delete and insert procedure internally.
- Slow and it changes the auto-increment id.
- All the fields have to be provided
Sqlite
Recommended
-- Try to update any existing row UPDATE players SET user_name='steven', age=32 WHERE user_name='steven'; -- Make sure it exists INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32);
Pros:
Works for all sqlite versions.
Cons:
Too long statement.
Alternative
This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.
INSERT INTO players (user_name, age) VALUES('steven', 32) ON CONFLICT(user_name) DO UPDATE SET age=excluded.age;
最后一次更新于2018-12-14
0 comment