有没有更好的方法来调整此查询?

时间:2013-03-14 11:44:10

标签: sql oracle performance

我有以下查询,想知道是否有更好的方法来调整它?

MERGE INTO target_table TARGET USING
(SELECT DISTINCT g1.column_name
FROM test_gtt1 g1,
test_gtt2 g2
WHERE g1.column_name = g2.column_name
AND g1.diff_id      IS NULL
AND g2.diff_id      IS NULL
UNION ALL
SELECT DISTINCT g1.column_name
FROM test_gtt1 g1,
test_gtt2 g2
WHERE 
g1.column_name  = g2.column_name
AND g1.diff_id = g2.diff_id
AND g1.diff_id IS NOT NULL
AND g2.diff_id IS NOT NULL
) SOURCE ON ( TARGET.column_name = SOURCE.column_name)
WHEN MATCHED THEN
UPDATE SET TARGET.column_name2 = 123;

2 个答案:

答案 0 :(得分:1)

这取决于数据类型,索引和生成的计划是什么(如果你提供了这个,那将会有所帮助。)

但是工会显然是多余的:

SELECT DISTINCT g1.column_name
FROM test_gtt1 g1,
test_gtt2 g2
WHERE g1.column_name = g2.column_name
AND ((g1.diff_id IS NULL
      AND g2.diff_id IS NULL)
     OR (g1.diff_id IS NOT NULL
         AND g2.diff_id IS NOT NULL))

<强>更新

我(在回复APC的评论时)发现使用....也可以得到相同的结果....

SELECT DISTINCT g1.column_name
FROM test_gtt1 g1,
test_gtt2 g2
WHERE g1.column_name = g2.column_name
AND DECODE(g1.diff_id, NULL, -1, 1)=DECODE(g2.diff_id, NULL, -1, 1);

答案 1 :(得分:-1)

如果您要将这两个集合与UNION合并,则无需测试diff_id is nulldiff_id is not null

       select * from foo where bar is null
       union all
       select * from foo where bar is not null

相同
       select * from foo