Mysql get last id of specific table

ぃ、小莉子 提交于 2019-12-03 07:21:04

问题


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


回答1:


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



回答2:


Is this what you are looking for?

SELECT id FROM blahblah ORDER BY id DESC LIMIT 1



回答3:


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.




回答4:


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.




回答5:


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




回答6:


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


来源:https://stackoverflow.com/questions/14255373/mysql-get-last-id-of-specific-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!