简体   繁体   English

SQL返回上次查询中受影响的行的值?

[英]SQL return values of affected rows in last query?

I have an SQL query which inserts a new record into table1 . 我有一个SQL查询,它将新记录插入到table1 The records 'id' is the PK ( field1 ) and has the auto increment property: 记录'id'是PK( field1 )并具有自动递增属性:

INSERT INTO table1 (field2, field3) VALUES ("Hello", "World")

My next query (immediately afterwards) inserts a record into table2 , and requires the id of the row which was affected in the previous query. 我的下一个查询(紧随其后)将一条记录插入table2 ,并要求在上一个查询中受影响的行的ID。

INSERT INTO table2 (field2) VALUES (PKValueOfAffectedRowInPreviousQuery)

Is there a function which can return a result set for the rows affected in a query, something along the lines of $result = $stmt->return_affected_records() so that I could access this field1 value? 是否有一个函数可以为查询中受影响的行返回结果集,类似$result = $stmt->return_affected_records()这样,以便我可以访问此field1值?

This is entirely different to returning the number of affected rows, which I know is received using $stmt->affected_rows . 这与返回受影响的行完全不同,我知道这是使用$stmt->affected_rows收到的。 I'm concerned with the values within those records affected. 我关心那些受影响的记录中的

I think you could do this with a select in between these two insert s: 我认为您可以在这两个insert之间进行select

$value1 = "Hello";
$value2 = "World";

INSERT INTO table1 (field2, field3) VALUES ($value1,$value2);

$sql = "SELECT field1 FROM table1 WHERE field2 ='" . $value1 . "' AND field3 = '" . $value2 . "'"; 

Now you just have to extract the id from the result and make your second insert. 现在,您只需要从结果中提取id并进行第二次插入即可。

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

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