Mysql get last id of specific table

2019-03-11 07:48发布

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

6条回答
Melony?
2楼-- · 2019-03-11 08:11

Is this what you are looking for?

SELECT id FROM blahblah ORDER BY id DESC LIMIT 1
查看更多
欢心
3楼-- · 2019-03-11 08:16

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楼-- · 2019-03-11 08:20

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楼-- · 2019-03-11 08:33

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);
查看更多
聊天终结者
6楼-- · 2019-03-11 08:35

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');
查看更多
戒情不戒烟
7楼-- · 2019-03-11 08:38

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

查看更多
登录 后发表回答