[英]Can one use the result of one query into another query within a single MySQL transaction?
I'm coding using PHP PDO and MySQL. 我正在使用PHP PDO和MySQL进行编码。
In that context, can I write a single transaction that would run a first query (or series of queries), and then use the result of this query as an input into another query? 在这种情况下,我可以编写单个事务来运行第一个查询(或一系列查询),然后将该查询的结果用作另一个查询的输入吗?
For example, I would like to (1) create a new record in table A and get the autoincremented ID in return, (2) create a new record in table B and get the autoincremented ID in return, (3) enter the IDs generated above from table A and B in two fields of a table C which represents the relation between A and B. 例如,我想(1)在表A中创建一个新记录并获取自动递增的ID,(2)在表B中创建一个新记录并获取自动递增的ID,(3)输入生成的ID以上来自表A和B的表C的两个字段中,该字段表示A和B之间的关系。
Can I do the above in a single transaction? 我可以单笔交易完成以上操作吗? Also, can I add some programming between each queries?
另外,我可以在每个查询之间添加一些编程吗?
Short answer: Yes . 简短的回答: 是的 。
Long answer: 长答案:
Absolutely, that's what transactions are designed for. 绝对是设计交易的目的。
As far as your SQL vendor supports transaction (mysql does on InnoDB tables) you can use them to execute a serie of query. 只要您的SQL供应商支持事务(mysql在InnoDB表上支持事务),您就可以使用它们执行一系列查询。
Also, can I add some programming between each queries?
另外,我可以在每个查询之间添加一些编程吗?
Yes, you can, however, make sure that if you're updating some third party, to rollback the change yourself. 是的,但是,您可以确保如果要更新某些第三方,请自己回滚更改。
Example: 例:
try {
$db->beginTransaction();
$db->exec('INSERT INTO tableA (id, column) VALUES (NULL, NOW())');
$db->exec('SELECT id FROM tableB ORDER BY id DESC LIMIT 1');
// ...
$httpClient->post(sprintf('/notify/foo/%d?value=ok', $id));
$db->commit();
} catch (\PDOException $e) {
$db->rollback();
$httpClient->post(sprintf('/notify/foo/%d?value=cancel', $id));
}
Note that you can aslo nest transaction and use SAVEPOINT
on InnoDB tables. 请注意,您还可以嵌套事务并在InnoDB表上使用
SAVEPOINT
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.