Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql get last id of specific table

I have to get last insert id from a specific inserted table?. Lets say i have this code:

INSERT INTO blahblah (test1, test 2) VALUES ('test1', 'test2');
INSERT INTO blahblah2 (test1, test 2) VALUES ('test1', 'test2');
INSERT INTO blahblah3 (test1, test 2, lastid) VALUES ('test1', 'test2', last id of blahblah);

How do i get the insert id of table blahblah in table blahblah3? LAST_INSERT_ID() only gives you the last insert id

Regards, Simon :)

like image 426
simon Avatar asked Jan 10 '13 10:01

simon


People also ask

How do I get the last insert ID from a specific table?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

How can I get the last ID from a table if its set to auto increment?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.

How do I get the last inserted row ID in SQL?

MySQL LAST_INSERT_ID() Function The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.


2 Answers

You can use LAST_INSERT_ID() function. Try this:

INSERT INTO blahblah (test1, test2) VALUES ('test1', 'test2');

SELECT LAST_INSERT_ID() INTO @blahblah;

INSERT INTO blahblah2 (test1, test2) VALUES ('test1', 'test2');

INSERT INTO blahblah3 (test1, test2, lastid) VALUES ('test1', 'test2', @blahblah);
like image 106
Saharsh Shah Avatar answered Sep 29 '22 02:09

Saharsh Shah


Is this what you are looking for?

SELECT id FROM blahblah ORDER BY id DESC LIMIT 1
like image 25
x4rf41 Avatar answered Sep 29 '22 02:09

x4rf41