简体   繁体   English

检索表的最后插入ID以在另一个表中用作外键

[英]retrieving last inserted ID of a table for using as Foreign key in another table

I have table(table1 and table2) that ID of table1 are foreign key of table2. 我有table(table1和table2),table1的ID是table2的外键。 in INSERT I want to save last ID inserted in table1 for insert to foreign key of table2. 在INSERT中我想保存插入到table1中的最后一个ID,以插入到table2的外键中。 In your idea what is best way for it? 在你的想法中,最好的方法是什么?

Use Like this in Your Code: 在您的代码中使用像这样:

$result= mysql_query("Your SelectQuery");   
$lastId  = mysql_insert_id();

And Use $lastId variable . 并使用$lastId变量。 And You Can Get Your REsult . 你可以得到你的REsult

You Can Also Use JOIN s For join 2 tables And use last_insert_id for table 1. 您还可以使用JOIN对于连接2表并使用last_insert_id表1。

使用LAST_INSERT_ID()函数获取最后插入的自动递增列的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM