Sql 使用“不存在”优化查询

Sql 使用“不存在”优化查询,sql,oracle10g,Sql,Oracle10g,我想在下面的查询中使用NOT EXIST优化我的查询,我如何才能做到这一点,并请解释它的执行计划 Select I_Ftn, I_Col, count(c.i_id_num) cnt From DSCL_ALL.W_CALENDER c Where c.UNIT_CODE= '01' AND c.i_g_vill = '45' and c.i_g_code = '1' and c.survey_year = '2012-2013' and c.i_number not in (selec

我想在下面的查询中使用NOT EXIST优化我的查询,我如何才能做到这一点,并请解释它的执行计划

 Select I_Ftn, I_Col, count(c.i_id_num) cnt 
From DSCL_ALL.W_CALENDER c 
Where c.UNIT_CODE= '01' 
AND c.i_g_vill = '45'
and c.i_g_code = '1'
and c.survey_year = '2012-2013'
and c.i_number not in (select m.m_indent from w_mill_pur m where m.unit_code = c.unit_code and m.m_vill = c.i_g_vill and m.m_grow = c.i_g_code)  
Group By I_Ftn, I_Col
ORDER BY I_ftn, I_col)

您可能想尝试以下方法:

Select I_Ftn, I_Col, count(c.i_id_num) cnt 
From DSCL_ALL.W_CALENDER c 
Where c.UNIT_CODE= '01' 
AND c.i_g_vill = '45'
and c.i_g_code = '1'
and c.survey_year = '2012-2013'
and not exists (select 1 from w_mill_pur m where m.unit_code = c.unit_code and m.m_vill = c.i_g_vill and m.m_grow = c.i_g_code and m.m_indent = c.i_number)  
Group By I_Ftn, I_Col
ORDER BY I_ftn, I_col)
由于添加了where子句,它的效率更高:Oracle能够运行更过滤的子查询,然后只测试结果集是否为空。 您可能还需要检查您是否有w_mill_pur的单位代码、m_vill、m_grow、m.m_缩进索引

非in-way要求在主查询中再加入一个联接,子查询结果集与主查询结果集


关于,

不存在和不存在之间有区别。请按ASKTOM-


Oracle在非条件下进行优化时非常聪明。如果您的语句会产生与原始语句相同的执行计划,我不会感到惊讶。我想这取决于可用的索引,但Oracle optimizer在这方面非常擅长。同时,拥有一个更好的原始查询仍然是一个更好的起点:哇,我以前的查询的执行时间是14.53,现在只需要1秒。谢谢FabienM。还有一件事我想在子查询中问一下,为什么我们使用select 1 from w_mill_pur m,其中m.unit…。您可以选择1、2、*,或者您在w_mill_pur中拥有的任何列元组。Oracle只会检查resultset的空性,不管它有什么内容。