我有一个INSERT INTO SELECT
语句,用源表中的;
解析的值填充表:
INSERT INTO PC_MATERIALS_BRIDGE (MATERIAL_BRIDGE_ID, VARIABLE_ID, MATERIAL_NAME)
SELECT PC_VAR_MATERIALS_BRIDGE_SEQ.NEXTVAL, VARIABLE_ID, MATERIAL_NAME FROM (SELECT DISTINCT E.VARIABLE_ID, LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) MATERIAL_NAME
FROM (SELECT VARIABLE_ID, MATERIALS FROM SRC_VARS_OCEAN_ALL WHERE MATERIALS IS NOT NULL AND MATERIALS != 'N/A) e
CONNECT BY LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) IS NOT NULL);
所以,源表中的数据
ID MATERIAL_NAME
1 paper
2 paper; plastic
将显示为
MATERIAL_BRIDGE_ID MATERIAL_NAME
1 paper
2 paper
3 plastic
在目标表中。
脚本运行良好;然而,它非常昂贵,因为源表有近40,000条记录,有些有三个值,例如paper; plastic; rubber
。我知道LEVEL
很贵。我将MATERIAL_NAME
设置为VARCHAR2(255 BYTE)
。不知道除了编写其他类型的查询之外如何改进(例如,递归但它可能很难)。 DISTINCT
也导致它减速吗?可能不再需要DISTINCT
,因为e.VARIABLE_ID
现在是主键。
答案 0 :(得分:2)
这是一种非常低效的方法。在下面的简单演示中删除DISTINCT时,您可以观察它导致问题的原因:
create table SRC_VARS_OCEAN_ALL(
VARIABLE_ID int,
MATERIALS varchar2(200)
);
insert into SRC_VARS_OCEAN_ALL values( 1, 'ala;ma;kota' );
insert into SRC_VARS_OCEAN_ALL values( 2, 'as;to;pies' );
insert into SRC_VARS_OCEAN_ALL values( 3, 'baba;jaga' );
insert into SRC_VARS_OCEAN_ALL values( 4, 'zupa;obiad' );
和
SELECT E.VARIABLE_ID, level,
LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) MATERIAL_NAME
FROM (
SELECT VARIABLE_ID, MATERIALS
FROM SRC_VARS_OCEAN_ALL
WHERE MATERIALS IS NOT NULL
AND MATERIALS != 'N/A'
) e
CONNECT BY LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) IS NOT NULL
order by 1,2;
VARIABLE_ID LEVEL MATERIAL_NAME
----------- ---------- -----------------
1 1 ala
1 2 ma
1 2 ma
1 2 ma
1 2 ma
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
1 3 kota
2 1 as
2 2 to
2 2 to
2 2 to
2 2 to
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
2 3 pies
3 1 baba
3 2 jaga
3 2 jaga
3 2 jaga
3 2 jaga
4 1 zupa
4 2 obiad
4 2 obiad
4 2 obiad
4 2 obiad
52 rows selected.
此查询仅为4个输入行生成 52个输出记录,其中包含10个值。你可以猜到4万会有多少 该查询生成数百个thausands甚至数百万行,然后DISTINCT对这个巨大的结果集进行排序,以消除重复。
以下查询应该执行得更好,因为它只生成10条记录,不多或少,只需执行此任务所需的记录:
SELECT a.VARIABLE_ID, b.lev_el,
trim( regexp_substr( a.MATERIALS, '[^;]+', 1, b.lev_el )) as MATERIAL_NAME
FROM SRC_VARS_OCEAN_ALL a
JOIN (
SELECT level as lev_el
FROM dual CONNECT BY level <= 100
) b
ON b.lev_el <= regexp_count( a.MATERIALS, ';' ) + 1
VARIABLE_ID LEV_EL MATERIAL_NAME
----------- ---------- --------------
1 1 ala
2 1 as
3 1 baba
4 1 zupa
1 2 ma
2 2 to
3 2 jaga
4 2 obiad
1 3 kota
2 3 pies
10 rows selected.
我假设每个列表中的值不超过100个(每个单独的行都有一个不超过100个值的列表),因此有FROM dual CONNECT BY level <= 100
子句。