简体   繁体   English

MySQL事务无法按预期工作

[英]Mysql transaction not working as expected

I have read a lot of documentation about mysql and transactions and from what I have understood is that when I use repeatable read isolation level in MySQL InnoDB and I start a transaction and I add some rows that when I do a select on those rows they aren't seen by MySQL in that transaction. 我已经阅读了很多有关mysql和事务的文档,据我了解,当我在MySQL InnoDB中使用可重复读取隔离级别并启动事务时,会添加一些行,当我在这些行上进行选择时,它们会MySQL在该事务中没有看到。 For example: 例如:

function dotransaction() {
  $result = mysqli_query("START TRANSACTION");
  if (!$result) return false;

  $result = mysqli_query("INSERT INTO t (f1,f2) VALUES (1,2)");
  if (!$result) {
    mysqli_query("ROLLBACK");
    return false;
  }

  $result = mysqli_query("INSERT INTO t (f1,f2) VALUES (3,4)");
  if (!$result) {
    mysqli_query("ROLLBACK");
    return false;
  }

  $result = mysqli_query("UPDATE t2 SET f3=(SELECT COUNT(*) AS count FROM t WHERE f1=1) WHERE f4=2");
  if (!$result) {
    mysqli_query("ROLLBACK");
    return false;
  }
}

If i execute the following code in PHP it really updates field f3 to 1 in table t2. 如果我在PHP中执行以下代码,它实际上会将表t2中的字段f3更新为1。 But I didn't expect that, because when I started the transaction the transaction reads a snapshot from the database and whereever I use a select statement it uses the first read snapshot and not the modifications to the table. 但是我没想到,因为当我开始事务时,该事务从数据库中读取快照,并且无论我在何处使用select语句,它都使用第一个读取快照而不是对表的修改。 When I take the select statement out of the UPDATE statement it also goves met count=1. 当我从UPDATE语句中取出select语句时,它也满足了count = 1。

You understand wrong. 你理解错了。

Changes to data made within transaction ARE visible within that transaction, so your SELECT statements will see updated rows. 在事务内可见对事务内数据所做的更改,因此您的SELECT语句将看到更新的行。

These changes however are not visible outside of the transaction, so if another user connects to the server at the same time, and queries these rows, he will see them in unaltered state. 但是,这些更改在事务外部是不可见的,因此,如果另一个用户同时连接到服务器并查询这些行,他将看到它们处于未更改状态。

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

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