15

我必须从特定的插入表中获取最后一个插入 ID?。可以说我有这个代码:

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

如何在表 blahblah3 中获取表 blahblah 的插入 ID?LAST_INSERT_ID() 只给你最后的插入 id

问候,西蒙 :)

4

6 回答 6

15

您可以使用LAST_INSERT_ID()函数。尝试这个:

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);
于 2013-01-10T10:14:32.870 回答
14

这是你想要的?

SELECT id FROM blahblah ORDER BY id DESC LIMIT 1
于 2013-01-10T10:13:35.873 回答
9

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.

于 2013-01-10T10:23:09.743 回答
2

您可以使用mysql_insert_id();函数来快速获得答案。

但是,如果您使用的是流量较大的网站,则存在准确结果的机会。

于 2013-01-10T10:15:55.573 回答
1

您可以使用LAST_INSERT_ID()函数。

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

 select LAST_INSERT_ID()

简而言之,将最后一个插入id保存在一个变量中,然后在blahblah3中使用

于 2013-01-10T10:14:15.703 回答
0

您还可以在 codeigniter As 中通过查询找到最后一个 id

$this->db->order_by('column name',"desc");
   $this->db->limit(1);
 $id=  $this->db->get('table name');
于 2016-02-07T16:34:18.970 回答