优化SQL语句

时间:2014-02-23 13:02:46

标签: sql

如果表B中按3列(A和B之间的匹配)分组的记录数小于7,我需要更新表A中的列。我写了下面的查询,但它运行的时间很长。请建议任何最佳查询或调整此。

update /*+ parallel(A) */ A set A.col4=0
where exists
      (select 1 
       from B 
       where A.col1=B.col1 and A.col2=B.col2
          and A.col3=B.col3 
       group by col1,col2,col3
       having count(*) < 7)

2 个答案:

答案 0 :(得分:0)

我的第一个建议是在B上创建一个索引:B(col1, col2, col3)

下一次尝试是将其切换为join

update A
    set col4 = 0
    from (select col1, col2, col3
          from B
          group by col1, col2, col3
          having count(*) < 7
         ) B
    where A.col1 = B.col1 and A.col2 = B.col2
          and A.col3 = B.col3 ;

答案 1 :(得分:0)

试试这个,

MERGE INTO A 
USING (
SELECT col1, col2, col3
      FROM B
      GROUP BY col1, col2, col3
      HAVING COUNT(*) > 7
) b ON (A.col1 = b.col1 AND A.col2=b.col2 AND A.col3= b.col3)
WHEN MATCHED THEN UPDATE
SET A.col4 = 0;

在SQL小提琴上查看:http://www.sqlfiddle.com/#!4/dcdf1/17

让我知道它是否有效!