This behaviour is by design:
If a stored procedure executes statements that change the value of LAST_INSERT_ID()
, the changed value is seen by statements that follow the procedure call.
For stored functions and triggers that change the value, the value is restored when the function or trigger ends, so following statements will not see a changed value.
Unfortunately this introduces a risk of inconsistencies between your table and objects
, as insertions could still happen outside of this procedure (this problem could be adressed with convoluted access restrictions on the table)
Save the value in a user variable:
CREATE TRIGGER
....
BEGIN
INSERT INTO objects (object_type) VALUES ('3');
SET NEW.id = LAST_INSERT_ID();
SET @myLastInsertID = LAST_INSERT_ID();
END //
INSERT INTO your_table... -- trigger the above
SELECT @myLastInsertID; -- here is your value
Simply get the value from object
;)
INSERT INTO your_table... -- trigger the above
SELECT MAX(autoinc_column) FROM objects; -- here is your value!
Workarounds 2 and 3 should be wrapped in a transaction to ensure no-one interferes with @myLastInsertID
or object
during the process.