Welcome Guest, Not a member yet? Register   Sign In
SQL - Insert or update if exist
#1

What is the best way to insert a new line (and if it exists just update already existing values? )

i know about this construction - but as fat as i am aware - it messes around with ID.. (if we use autoinceremnt)
Code:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
 ON DUPLICATE KEY UPDATE c=c+1;


I also know obvious decision - just check if the line already exist - 

just - simple if statement - 

but i am afraid of loosing atomicity of this operation. In this case possible such scenario - 
Two users are inserting one line, and check query may return false (the line doesn't exist) but before inserting newline another script makes it faster and we got an error (because in this case we need to use UPDATE instead of INSERT operation..)
Reply
#2

You do an insert with the data and if you've got an existing unique key (which isn't auto-incremented), if it exists, the insert will throw an error.

Catch the error and then do an update.

Or

Use auto-incremented primary key and all inserts will be on a new line.

Or

Use the $this->db->sql("") and use the on duplicate key SQL to make it happen.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB