如何改进更新子查询中引用的表的字段

时间:2018-07-11 03:43:37

标签: sql oracle oracle11g sql-update query-performance

我有一个被截断的表,然后每次由一个进程加载数十万条记录。接下来的过程需要通过基本查找各种其他表中的值,同时利用现有更新表自身的某些列作为参考来为每条记录(没有值)更新几列(在下面的示例中,可以是{ {1}}和TABLE_A.P1),例如:

TABLE_A.P2

运行此类更新时,会话超时。我的问题是,在上述情况下,是否有更好的方式编写此更新?

2 个答案:

答案 0 :(得分:1)

您可能会发现单独的更新语句更快:

UPDATE TABLE_A A
  SET A.COL1 = (SELECT B.COL_BX
                  FROM TABLE_B B
                  WHERE B.P1 = A.P1);

UPDATE TABLE_A A
  SET A.COL2 = (SELECT D.COL_DY
                  FROM TABLE_C C
                  INNER JOIN TABLE_D D
                    ON C.H1 = D.H1
                  WHERE C.P1 = A.P1);

UPDATE TABLE_A A
  SET A.COL3 = (SELECT G.COL_GZ
                  FROM TABLE_E E
                  INNER JOIN TABLE_F F
                    ON E.N1 = F.N1
                  LEFT OUTER JOIN TABLE_G G
                    ON G.M1 = F.M1
                  WHERE E.P1 = A.P1 AND
                        E.P2 = A.P2);

好运。

答案 1 :(得分:1)

您可以尝试以下操作:

UPDATE TABLE_A 
  SET TABLE_A.COL1 = B.COL_BX
From 
  TABLE_A A
INNER JOIN 
  TABLE_B B
  ON B.P1 = A.P1;

UPDATE TABLE_A 
  SET TABLE_A.COL2 = D.COL_DY
From 
  TABLE_A A
INNER JOIN 
  TABLE_C C
  ON C.P1 = A.P1
INNER JOIN 
  TABLE_D D
  ON C.H1 = D.H1;

UPDATE TABLE_A 
  SET TABLE_A.COL3 = G.COL_GZ
From 
  TABLE_A A
INNER JOIN 
  TABLE_E E
  ON E.P1 = A.P1
  AND E.P2 = A.P2
INNER JOIN 
  TABLE_F F
  ON E.N1 = F.N1
LEFT OUTER JOIN 
  TABLE_G G
  ON G.M1 = F.M1;

我不知道有关您的表结构的详细信息,但是您可以将这3个更新组合为如下所示的一个更新,但这完全取决于您的表结构。

UPDATE TABLE_A 
  SET 
  TABLE_A.COL1 = B.COL_BX,
  TABLE_A.COL2 = D.COL_DY,
  TABLE_A.COL3 = G.COL_GZ
From 
  TABLE_A A
LEFT OUTER JOIN 
  TABLE_B B
  ON B.P1 = A.P1
LEFT OUTER JOIN 
  TABLE_C C
  ON C.P1 = A.P1
LEFT OUTER JOIN 
  TABLE_D D
  ON C.H1 = D.H1
LEFT OUTER JOIN
  TABLE_E E
  ON E.P1 = A.P1
  AND E.P2 = A.P2
LEFT OUTER JOIN 
  TABLE_F F
  ON E.N1 = F.N1
LEFT OUTER JOIN 
  TABLE_G G
  ON G.M1 = F.M1;