首次使用DB2。我有一个执行联合的存储过程,无论如何都可以尝试。该程序超时。联合两侧的select语句在单独完成时快速执行,没有问题。工会为什么会这样做?
这是proc的一些sudo代码,假设数据类型是int或string,并且它们在比较或联合时匹配,除非在SQL中另有说明:
DECLARE Foo CURSOR WITH RETURN FOR
Select STRIP(A.Name) as my_Name,
Case A.Number
when 2 then '(' || strip(char(A.Number)) || ')' strip(B.num)
when 3 then '(' || strip(char(A.Number)) || ')' strip(C.num)
when 4 then '(' || strip(char(A.Number)) || ')' strip(D.num)
when 5 then '(' || strip(char(A.Number)) || ')' strip(E.num)
when 6 then '(' || strip(char(A.Number)) || ')' strip(F.num)
end as my_number
FROM A
left outer join B on A.Number= 2 and A.Name = B.Name
left outer join C on A.Number= 3 and C.Name = B.Name
left outer join D on A.Number= 4 and D.Name = B.Name
left outer join E on A.Number= 5 and E.Name = B.Name
left outer join F on A.Number= 6 and F.Name = B.Name
,session.Temp_Result X
WHERE X.ID = A.ID
GROUP BY A.Number, A.Name, B.Name, C.Name, D.Name, E.Name, F.Name
for fetch only ur;
DROP TABLE Session.Temp_Result;
DECLARE GLOBAL TEMPORARY TABLE session.Temp_Result
( ID DECIMAL(18,0)
);
INSERT INTO session.Temp_Result
select X.ID
from Z, Y, X, Q
where Z.num = 6
and Z.ID = Y.ID2
and Y.GROUPA = 'ABC'
and Y.GROUPB = 'DEF'
and Y.ID = X.ID2
and X.ID = Q.ID
union
select W.ID
from Z, Y, W
where Z.num = 6
and Z.ID = Y.ID2
and Y.GROUPA = 'ABC'
and Y.GROUPB = 'DEF'
and Y.ID = W.ID2
group by ID;
OPEN C_HIERARCHIES;
答案 0 :(得分:2)
尝试使用“with”语句进行查询。
DECLARE GLOBAL TEMPORARY TABLE session.Temp_Result (
ID DECIMAL(18,0))
WITH REPLACE;
INSERT INTO session.Temp_Result
(ID)
WITH Q1(Y_ID)
AS (
SELECT Y.ID
FROM Z
INNER JOIN Y ON Z.ID = Y.ID2
WHERE Z.NUM = 6 AND Y.GROUPA = 'ABC' AND Y.GROUPB = 'DEF')
SELECT X.ID
FROM X
INNER JOIN Q1 ON X.ID2 = Q1.Y_ID
WHERE EXISTS(SELECT 1 FROM Q WHERE Q.ID = X.ID)
UNION
SELECT DISTINCT W.ID
FROM W
INNER JOIN Q1 ON W.ID2 = Q1.Y_ID
如果没有用,请尝试使用“Explain SQL”作为select语句。也许你应该创建一些索引......
答案 1 :(得分:1)
我的猜测是原始代码缺少伪代码中存在的连接条件。您应该使用正确的连接语法重写查询以验证查询。
在任何情况下,如果每个子查询运行得很快并且联合有一些不正常的后果,你可以尝试将它分成两个插入:
INSERT INTO session.Temp_Result
select X.ID
from Z, Y, X, Q
where Z.num = 6
and Z.ID = Y.ID2
and Y.GROUPA = 'ABC'
and Y.GROUPB = 'DEF'
and Y.ID = X.ID2
and X.ID = Q.ID;
INSERT INTO session.Temp_Result
select W.ID
from Z, Y, W
where Z.num = 6
and Z.ID = Y.ID2
and Y.GROUPA = 'ABC'
and Y.GROUPB = 'DEF'
and Y.ID = W.ID2
group by ID;
然后您可以将Temp_Result查询为:
select distinct id from TempResult
删除重复项似乎是不必要的,因为数据太小,但您也可以直接执行此操作。