2015-12-02 53 views
0

我有以下查询我试图优化:创建甲骨文内嵌视图

select * from table1 where header_id in 
(select b.header_id from table2 b where event_id in 
(select d.accounting_event_id from table3 d where d.invoice_id=1234 
union select aida.bc_event_id from table3 aida where ida.invoice_id=1234 
union select d.accounting_event_id from table4 d where d.invoice_id=1234 
union select d.accounting_event_id from table5 d where d.check_id in (select a.check_id from table4 a where a.invoice_id=1234) 
union select d.accounting_event_id from table6 d where d.invoice_id=1234)) 

的问题似乎是与表2的嵌套循环。
一种可能性是为所有联合创建一个内联视图,然后将视图加入到表2中,以便它不会一遍又一遍地执行联合。
我将如何创建这样的内联视图? 感谢您的任何信息。

+2

是什么(从可疑的表结构除外)问题 – kevinsky

+0

我想,因为它正在以优化SQL太长。基于一些研究,我在这个sql上运行了一些工具,这个问题似乎与table2上的嵌套循环有关。所以看起来像一个解决方案可以创建一个内联视图,但不知道如何做到这一点。 –

回答

0

如果可能使用你可以尝试EXISTS,而不是在解决了嵌套循环问题:

WITH t as (
SELECT d.accounting_event_id 
    FROM table3 d 
WHERE d.invoice_id = 1234 
UNION ALL 
SELECT aida.bc_event_id 
    FROM table3 aida 
WHERE ida.invoice_id = 1234 
UNION ALL 
SELECT d.accounting_event_id 
    FROM table4 d 
WHERE d.invoice_id = 1234 
UNION ALL 
SELECT d.accounting_event_id 
    FROM table5 d 
WHERE d.check_id IN (SELECT a.check_id FROM table4 a WHERE a.invoice_id = 1234) 
UNION ALL 
SELECT d.accounting_event_id 
    FROM table6 d 
WHERE d.invoice_id = 1234) 
-- 
SELECT * 
    FROM table1 t1 
WHERE EXISTS (SELECT 1 
       FROM table2 b 
       WHERE t1.header_id = b.header_id 
        AND EXISTS (SELECT 1 
           FROM t 
           WHERE t.accounting_event_id = b.event_id)) 
+0

我必须保留为一个sql –

+0

这是一条SQL语句。虽然它只是重新安排部件,但我怀疑它是否会对性能产生实际影响。 – APC