6. 自己結合SQL例
? Window関数を用いて書換可能なSQL
※左記抽出対象行
6
id val1 val2
1 50a
1 123b
1 132c
2 44d
2 111e
3 32f
3 13g
3 89h
select id,val1,val2 from tab1 as a, (select
id,max(val1) as val1 from tab1 group by id)
as b where a.id=b.id and a.val1=b.val2;
select id,val1,val2 from (select id,val1,val2,
row_number() over(partition by id order by
val1 desc) row_number from tab1) where
row_number=1;
Tuning前 (3.94秒)
Tuning後 (2.66秒)
14. Step4: 比較機能
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core', 'K_SELECT',
'TOKEN', 'SELECT']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core',
'result_column', 'expr', 'column_name',
'any_name', 'IDENTIFIER', 'TOKEN']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core',
'result_column', 'expr', 'column_name',
'any_name', 'IDENTIFIER', 'TOKEN']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core', 'K_FROM',
'TOKEN', 'from']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core',
'table_or_subquery', 'table_name', 'any_name',
'IDENTIFIER', 'TOKEN', 'tab1']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core', 'K_SELECT',
'TOKEN', 'SELECT']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core', 'result_column',
'expr', 'column_name', 'any_name', 'IDENTIFIER',
'TOKEN']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core', 'K_FROM',
'TOKEN', 'from']
['', 'parse', 'sql_stmt_list', 'sql_stmt',
'factored_select_stmt', 'select_core',
'table_or_subquery', 'table_name', 'any_name',
'IDENTIFIER', 'TOKEN', 'tab1']
T
r
u
e
T
r
u
e
T
r
u
e
T
r
u
e
検査対象SQLクエリリスト
Select id,name from tab1
自己結合SQLクエリパターンリスト
Select col1 from tab1
全ての自己結合SQLクエリパターンリストがマッチした
場合、書換可能な自己結合SQLクエリとして判定
15. 作成した自己結合SQLクエリパターン1
特定列の最大?最小値をキーとした自己結合
1. SELECT COL1,COL2 FROM TAB1 A,(SELECT COL1,MAX(COL2) FROM TAB1 GROUP
BY COL1) B WHERE A.COL1=B.COL1 AND A.COL2=B.COL2
2. SELECT COL1 FROM TAB1 WHERE COL2 = (SELECT MAX(COL2) FROM TAB1)
3. SELECT COL1,COL2,COL3 FROM TAB1 A INNER JOIN (SELECT
COL1,COL2,MAX(COL3) COL3 FROM TAB1 GROUP BY COL1,COL2) B
ON A.COL1=B.COL1 WHERE A.COL2=B.COL2 AND A.COL3=B.COL3
4. SELECT * FROM TAB1 JOIN TAB2 ON TAB1.COL2=TAB2.COL2
INNER JOIN TAB3 ON
TAB3.COL3 = (SELECT MAX(COL3) FROM TAB3)
16. 作成した自己結合SQLクエリパターン2
特定列をキーとした自己結合
1. SELECT COL1 FROM TAB1 WHERE COL2 IN (SELECT COL2 FROM TAB1)
2. SELECT COL2 FROM TAB1 A,TAB1 B WHERE A.COL1=B.COL1
3. SELECT COL1,COL2 FROM TAB1 A JOIN TAB1 B ON A.COL1=B.COL1
Union句による自己結合
1. SELECT COL1 FROM TAB1 UNION SELECT COL1 FROM TAB1