简体   繁体   English

如何从事务中的特定查询中检索last_insert_id?

[英]How can I retrieve a last_insert_id from a specific query in a transaction?

I have a mysql transaction with three queries 我有一个带有三个查询的mysql事务

In the third query I am trying to pull last_insert_id values from the two previous queries. 在第三个查询中,我尝试从前两个查询中提取last_insert_id值。

VALUES ('".$result1[last_id]."','".$result2[last_id]."')";

But it doesn't work. 但这是行不通的。 Any suggestions? 有什么建议么?

You should get the last insert ID first, and then inject it into the query. 您应该首先获取最后一个插入ID,然后将其插入查询中。 Assuming you're using the mysql_ functions: 假设您正在使用mysql_函数:

mysql_query($query1);
$id1 = mysql_insert_id();

mysql_query($query2);
$id2 = mysql_insert_id();

$query3 = "INSERT INTO ... VALUES (".$id1.", ".$id2.");";
mysql_query($query3);

Assuming that you are using MySQL database. 假设您正在使用MySQL数据库。 You can get id like: 您可以获取如下ID:

mysql_query($first_query);
$first_result_id = mysql_insert_id();

mysql_query($second_query);
$second_result_id = mysql_insert_id();

$third_query = "INSERT INTO table  (column1, column2) VALUES (".$first_result_id .", ".$second_result_id .");";
mysql_query($third_query);

Hope this helps 希望这可以帮助

You can use MySQL to 您可以使用MySQL来

SELECT LAST_INSERT_ID()

which will retrieve the last insert ID in the given transaction. 它将检索给定事务中的最后一个插入ID。 You can also do this in other DBMS, but you are obviously using MySQL. 您也可以在其他DBMS中执行此操作,但是显然您正在使用MySQL。

Since you are, the MySQL APIs in php have shortcuts for this too: 既然如此,php中的MySQL API也有相应的快捷方式:

//mysql_*
$id = mysql_insert_id();

//PDO
$pdo = PDO_OBJECT;
$pdo->query();
$id = $pdo->lastInsertId();

//mysqli
$my = MYSQLI_OBJECT;
$my->query();
$id = $my->insert_id;

NOTE: @HopeIHelped's answer is misleading. 注意: @HopeIHelped的答案具有误导性。 There is no race condition as long as you are within the same transaction. 只要您在同一笔交易中,就没有竞争条件。 LAST_INSERT_ID() retrieves the last ID in the given transactions (and the APIs above do as well), so even if you have this file running a ton of transactions and interlocking queries at once, you can use them safely. LAST_INSERT_ID()检索给定事务中的最后一个ID(并且上面的API也是如此),因此,即使您使该文件一次运行大量事务并互锁查询,也可以安全地使用它们。

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

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