I've searched around but didn't find if it's possible.
I've this MySQL query:
INSERT INTO table (id,a,b,c,d,e,f,g) VALUES (1,2,3,4,5,6,7,8)
Field id has a "unique index", so there can't be two of them. Now if the same id is already present in the database, I'd like to update it. But do I really have to specify all these field again, like:
INSERT INTO table (id,a,b,c,d,e,f,g) VALUES (1,2,3,4,5,6,7,8)
ON DUPLICATE KEY UPDATE a=2,b=3,c=4,d=5,e=6,f=7,g=8
Or:
INSERT INTO table (id,a,b,c,d,e,f,g) VALUES (1,2,3,4,5,6,7,8)
ON DUPLICATE KEY UPDATE a=VALUES(a),b=VALUES(b),c=VALUES(c),d=VALUES(d),e=VALUES(e),f=VALUES(f),g=VALUES(g)
I've specified everything already in the insert...
A extra note, I'd like to use the work around to get the ID to!
id=LAST_INSERT_ID(id)
I hope somebody can tell me what the most efficient way is.
Just in case you are able to utilize a scripting language to prepare your SQL queries, you could reuse field=value pairs by using
SET
instead of(a,b,c) VALUES(a,b,c)
.An example with PHP:
Example table:
you can use insert ignore for such case, it will ignore if it gets duplicate records INSERT IGNORE ... ; -- without ON DUPLICATE KEY
The
UPDATE
statement is given so that older fields can be updated to new value. If your older values are the same as your new ones, why would you need to update it in any case?For eg. if your columns
a
tog
are already set as2
to8
; there would be no need to re-update it.Alternatively, you can use:
To get the
id
fromLAST_INSERT_ID
; you need to specify the backend app you're using for the same.For LuaSQL, a
conn:getlastautoid()
fetches the value.There is no other way, I have to specify everything twice. First for the insert, second in the update case.
You may want to consider using
REPLACE INTO
syntax, but be warned, upon duplicate PRIMARY / UNIQUE key, it DELETES the row and INSERTS a new one.You won't need to re-specify all the fields. However, you should consider the possible performance reduction (depends on your table design).
Caveats:
Here is a solution to your problem:
I've tried to solve problem like yours & I want to suggest to test from simple aspect.
Follow these steps: Learn from simple solution.
Step 1: Create a table schema using this SQL Query:
Step 2: Create an index of two columns to prevent duplicate data using following SQL Query:
or, Create an index of two column from GUI as follows:
Step 3: Update if exist, insert if not using following queries: