What is the equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
+4
A:
This is what you are looking for:
LAST_INSERT_ID()
In response to the OP's comment, I created the following bench test:
CREATE TABLE Foo
(
FooId INT AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE Bar
(
BarId INT AUTO_INCREMENT PRIMARY KEY
);
INSERT INTO Bar () VALUES ();
INSERT INTO Bar () VALUES ();
INSERT INTO Bar () VALUES ();
INSERT INTO Bar () VALUES ();
INSERT INTO Bar () VALUES ();
CREATE TRIGGER FooTrigger AFTER INSERT ON Foo
FOR EACH ROW BEGIN
INSERT INTO Bar () VALUES ();
END;
INSERT INTO Foo () VALUES (); SELECT LAST_INSERT_ID();
This returns:
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 5 |
+------------------+
So it uses the LAST_INSERT_ID()
of the original table and not the table INSERT
ed into inside the trigger.
Sean Bright
2009-02-18 12:07:57
Thanks Sean. How does it behave when the table I am inserting the data into has a trigger that inserts data in another table which has an autoincrement field too? Would it return the ID of the original table or the one affected by the trigger?
kristof
2009-02-18 12:16:47
Thanks Sean for testing this
kristof
2009-02-19 09:58:38