Вопрос

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 :)

Это было полезно?

Решение

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);

Другие советы

Is this what you are looking for?

SELECT id FROM blahblah ORDER BY id DESC LIMIT 1

If you want to do it in a single statement use:

INSERT INTO blahblah3 (test1, test2, lastid)
VALUES ('test1', 'test2', (select MAX(id) FROM blahblah));

This way you don't need to save any variables beforehand which assures you'll get the latest ID at that exact moment.

You can use mysql_insert_id(); function to get a quick answer.

But if you are using a heavy traffic site, chances of in accurate results exist.

You can use LAST_INSERT_ID() function.

INSERT INTO blahblah (test1, test 2) VALUES ('test1', 'test2');
    //this query will return id. Save it in one variable

 select LAST_INSERT_ID()

In short, save the last insert id in one variable and then use it in blahblah3

you can also find last id by query in codeigniter As

$this->db->order_by('column name',"desc");
   $this->db->limit(1);
 $id=  $this->db->get('table name');
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top