回答編集履歴

1

調整

2023/08/29 07:40

投稿

yambejp
yambejp

スコア116455

test CHANGED
@@ -9,10 +9,25 @@
9
9
  に対して、遅延のトランザクションのテストは3パターンあります
10
10
  # パターン1
11
11
  ```SQL
12
- 先行実行
13
12
  /*先発実行*/
14
13
  start transaction;
15
- select id2 from tbl limit 999 for update;
14
+ select id2 from tbl for update;
15
+ select sleep(5);
16
+ insert into tbl(id2,val) values
17
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),400),
18
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),500);
19
+ commit;
20
+
21
+ /*後発実行*/
22
+ insert into tbl(id2,val) values
23
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),600),
24
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),700);
25
+ ```
26
+ # パターン2
27
+ ```SQL
28
+ /*先発実行*/
29
+ start transaction;
30
+ select id2 from tbl for update;
16
31
  insert into tbl(id2,val) values
17
32
  ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),400),
18
33
  ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),500);
@@ -23,3 +38,24 @@
23
38
  insert into tbl(id2,val) values
24
39
  ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),600),
25
40
  ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),700);
41
+ ```
42
+ # パターン3
43
+ ```SQL
44
+ /*先発実行*/
45
+ start transaction;
46
+ select sleep(5);
47
+ select id2 from tbl for update;
48
+ insert into tbl(id2,val) values
49
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),400),
50
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),500);
51
+ commit;
52
+
53
+ /*後発実行*/
54
+ insert into tbl(id2,val) values
55
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),600),
56
+ ((select id2 from (select max(id2)+1 as id2 from tbl) as dummy),700);
57
+ ```
58
+ トランザクションの考え方からすれば遅延はパターン1に限られます
59
+ ただし実質パターン2でも問題ないでしょう
60
+ パターン3のようにfor updateの前に遅延が発生した場合は、後発クエリのほうが先行して実行される可能性があります。
61
+ したがって後発クエリもトランザクションで実行し、優先順位を確定させてください