参考
SQL
1create table tbl (id1 int primary key auto_increment,id2 int,val int);
2insert into tbl(id2,val) values
3(1,100),
4(2,200),
5(3,300);
に対して、遅延のトランザクションのテストは3パターンあります
パターン1
SQL
1/*先発実行*/
2start transaction;
3select id2 from tbl for update;
4select sleep(5);
5insert into tbl(id2,val) values
6((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),400),
7((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),500);
8commit;
9
10/*後発実行*/
11insert into tbl(id2,val) values
12((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),600),
13((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),700);
パターン2
SQL
1/*先発実行*/
2start transaction;
3select id2 from tbl for update;
4insert into tbl(id2,val) values
5((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),400),
6((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),500);
7select sleep(5);
8commit;
9
10/*後発実行*/
11insert into tbl(id2,val) values
12((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),600),
13((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),700);
パターン3
SQL
1/*先発実行*/
2start transaction;
3select sleep(5);
4select id2 from tbl for update;
5insert into tbl(id2,val) values
6((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),400),
7((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),500);
8commit;
9
10/*後発実行*/
11insert into tbl(id2,val) values
12((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),600),
13((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),700);
トランザクションの考え方からすれば遅延はパターン1に限られます
ただし実質パターン2でも問題ないでしょう
パターン3のようにfor updateの前に遅延が発生した場合は、後発クエリのほうが先行して実行される可能性があります。
したがって後発クエリもトランザクションで実行し、優先順位を確定させてください