If a table contains an AUTO_INCREMENT
column and INSERT ... UPDATE
inserts a row, the LAST_INSERT_ID()
function returns the AUTO_INCREMENT
value. If the statement updates a row instead, LAST_INSERT_ID()
is not meaningful. However, you can work around this by using LAST_INSERT_ID(expr)
. Suppose that id
is the AUTO_INCREMENT
column. To make LAST_INSERT_ID()
meaningful for updates, insert rows as follows:
INSERT INTO table (a, b, c) VALUES (1, 2, 3)
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), c = 3;
Found it on this link. I've never tried it though, but it might help you.
EDIT 1
You might want to check out REPLACE:
REPLACE INTO table1 (column1, column2, column3) VALUES (param1, param2, param3);
This should work for tables with correct PRIMARY KEY
/UNIQUE INDEX
.
In the end, you'll just have to stick with:
IF (VALUES EXISTS ON TABLE ...)
UPDATE ...
SELECT Id;
ELSE
INSERT ...
RETURN last_insert_id();
END IF