2014-09-02 44 views
0

如何交談下面的代碼使用了相同的結果一起獲得(不使用子查詢)排除使用加入無子查詢

select a_key from table_a a 
inner join table_b b --in my code I've 5 joins like that 
    on a.a_key=b.a_key 
where a_key not in 
    (select a_key from table_c  --and conditions within this brackets also 
     where var_a beteween table_c.col1 and table_c.col2 
     or var_b beteween table_c.col1 and table_c.col2 
    ) 
+0

您可以將子查詢結果首先存儲在臨時表中,然後在第二個查詢中加入該表。 – ItalianStallion 2014-09-02 17:53:51

+0

爲什麼你要重寫查詢?演出內容嗎?你應該增加我的想法。 – user2672165 2014-09-02 18:04:51

+0

是的性能,優化,聯接比子查詢更快 – user3376246 2014-09-02 18:07:28

回答

0

以下是基本相同的邏輯:

select a_key 
from table_a a inner join 
    table_b b 
    on a.a_key = b.a_key left join 
    table_c c 
    on (var_a between table_c.col1 and table_c.col2 or 
     var_b between table_c.col1 and table_c.col2 
     ) and 
     a.a_key = c.a_key 
where c.a_key is null; 

您應該預先具有表別名的列。 a_key列在您的原始文件中不明確,列var_avar_b也是如此。

如果任何匹配的table_c.a_key的值爲NULL,則它們稍有不同。在這種情況下,join版本的行爲可能更像您所期望的。

+0

枝把我的編輯忘記寫下來 – user3376246 2014-09-02 17:55:33