<?php
$this->link->beginTransaction();
$this->link->query('select yourcolumn from yourtable where yourcondition for update');
sleep(20);
$this->link->commit();
然后打开mysql工作台并尝试运行以下
begin;
select count(yourcolumn) from yourtable where yourcondition for update;
// will lock here
请记住在选择列数据时始终打开事务并使用 select 进行更新
当您在工作台中运行以下内容时(在上面的 php 脚本正在运行时),我已经测试了以下内容,这些内容也受锁定保护
update yourtable set yourcolumn=yourvalue where yourcondition;
// will lock here because php has obtained lock, no need to use transaction here
但是,当您在工作台中运行以下内容时(上述 php 脚本正在运行),以下内容不受锁定保护
select yourcolumn from yourtable where yourcondition;
// will immediately return resulset because you are not using transaction AND "for update"
此外,您可以查看所有使用 beginTransaction 的代码,因为长时间运行的事务会导致长表锁定。一个例子是你在一个导入文件操作中只有一个事务。将第一条记录插入表后,表将被锁定。
begin;
insert into yourtable values yourvalues;
// will acquire lock here, other mysql workbench will be deadlock
// until your whole import operation is done and rollback/commit your upload