-1

我在 Oracle 上有这个声明,但是速度很慢。是否可以对其进行优化?

SELECT col2.column_name 
FROM all_constraints cons, all_cons_columns col, all_cons_columns col2, all_constraints cons2
WHERE cons.owner = 'OWNER' 
AND cons.table_name = 'TABLE'
AND col.constraint_name = cons.constraint_name 
AND cons.constraint_type  = 'P'
AND col2.column_name  = col.column_name 
AND col2.table_name = col.table_name 
AND col2.owner = col.owner 
AND cons2.constraint_name = col2.constraint_name 
AND cons2.constraint_type = 'R'
AND cons2.r_constraint_name 
IN (SELECT parentcol.constraint_name FROM all_cons_columns parentCol WHERE parentcol.owner = 'OWNER2' AND parentcol.table_name = 'TABLE2')

我试过这个(返回相同的结果),但它仍然很慢

SELECT *
FROM all_constraints cons, all_cons_columns col
WHERE col.table_name = 'TABLE2' AND col.Owner = 'OWNER2'
AND col.constraint_name = cons.constraint_name AND cons.constraint_type = 'P' AND 
col.column_name IN 
(
  SELECT col2.column_name
  FROM all_constraints cons2, all_cons_columns col2
  WHERE col2.table_name = 'TABLE2' AND col2.Owner = 'OWNER2'
  AND col2.constraint_name = cons2.constraint_name AND cons2.constraint_type = 'R'
  AND cons2.r_constraint_name IN
  (
    SELECT cons3.constraint_name
    FROM all_constraints cons3, all_cons_columns col3
    WHERE col3.table_name = 'TABLE' AND col3.Owner = 'OWNER'
    AND col3.constraint_name = cons3.constraint_name AND cons3.constraint_type = 'P' 
  )
)
4

1 回答 1

0

您如何尝试重写它以避免重复命中字典(all_ 视图有时性能不佳,因为它们会进行大量权限检查)。

例如试试这个:

with tab as (select cons.owner, cons.constraint_name, cons.r_constraint_name, 
                    cons.constraint_type, cons.table_name, col.column_name 
               from all_constraints cons
                    inner join all_cons_columns col 
                            on col.constraint_name = cons.constraint_name
                           and col.owner = cons.owner
              where col.table_name in ('<CHILD TAB>', '<PARENT TAB>')
                and col.owner = '<OWNER>'
                and cons.constraint_type in ( 'P', 'R' ))
select col.owner, col.constraint_name, col.table_name, col.column_name
  from tab col
       inner join tab col2
               on col.column_name = col2.column_name 
              and col.table_name = col2.table_name
              and col.owner = col2.owner
       inner join tab col3
               on col2.r_constraint_name = col3.constraint_name
 where col2.constraint_type = 'R'
   and col.table_name = '<CHILD TAB>'
   and col2.table_name = '<CHILD TAB>'
   and col.constraint_type = 'P'
   and col3.table_name = '<PARENT TAB>'
   and col3.constraint_type = 'P';
于 2012-11-27T13:44:04.910 回答