简化并降低反连接查询的成本

时间:2010-12-29 11:00:22

标签: oracle

您能否帮我简化并降低以下查询的费用?

我尝试将它作为一个与NOT EXISTS相关的子查询,但它没有给我任何输出。

请注意,主要和内部查询中的表格与“table_1”相同。

SELECT *
FROM Table_1 A
WHERE A.Col1              = 'abcd'
AND (A.Col2, A.Col3) NOT IN
  (SELECT Col2,
    Col3
  FROM Table_1 B
  WHERE (B.Col4 IN (1,2,3)
  And B.Col5    In ('x','y'))
  OR (B.Col4     = 1 AND B.Col5     = 'z' AND B.Col6     = 'f')
  ))

提前致谢, Savitha

3 个答案:

答案 0 :(得分:0)

尝试以下操作以查看是否有帮助:

SELECT A.*
  FROM (SELECT *
          FROM Table_1
           WHERE A.Col1 = 'abcd') A
LEFT OUTER JOIN (SELECT Col2, Col3, primary_key_column
                   FROM Table_1
                   WHERE (B.Col4 IN (1, 2, 3) AND
                          B.Col5 IN ('x', 'y')) OR
                         (B.Col4 = 1 AND
                          B.Col5 = 'z' AND
                          B.Col6 = 'f')) B
  ON (B.Col2 = A.Col2 AND B.Col3 = A.Col3)
WHERE B.primary_key_column IS NULL;

你应该在TABLE1(Col1),TABLE1(Col2,Col3)和TABLE1的主键列上有索引,无论它是什么。

分享并享受。

答案 1 :(得分:0)

通常很多关于反复试验。除了使用not exists和outer join之外,由于这是一个自连接,它应该减少到一个表...

SELECT *
FROM Table_1
WHERE col1 = 'abcd'
AND NOT
   (col4 IN (1,2,3)
      AND col5 IN ('x','y')
)
AND NOT (col4=1
  AND col5='z'
  AND col6='f'
);

或者您可以尝试使用MINUS ......

SELECT *
FROM Table_1
WHERE col1 = 'abcd'
MINUS
SELECT *
FROM Table_1
WHERE col1 = 'abcd'
AND ((col4 IN (1,2,3)
      AND col5 IN ('x','y'))
   OR (col4=1
      AND col5='z'
      AND col6='f')  
);

最有效的解决方案将取决于数据的传播。

  

但它没有给我任何输出

你确定有匹配的行吗?

答案 2 :(得分:0)

很酷的回答。 如果使用索引,则以下内容不应相同

SELECT A.*
  FROM Table_1 A
LEFT OUTER JOIN (SELECT Col2, Col3, primary_key_column
                   FROM Table_1
                   WHERE (B.Col4 IN (1, 2, 3) AND
                          B.Col5 IN ('x', 'y')) OR
                         (B.Col4 = 1 AND
                          B.Col5 = 'z' AND
                          B.Col6 = 'f')) B
  ON (B.Col2 = A.Col2 AND B.Col3 = A.Col3)
WHERE A.Col1 = 'abcd'
  and B.primary_key_column IS NULL;