左连接查询而不是不存在

时间:2013-04-16 18:03:23

标签: sql left-join max not-exists

我有一个“不存在的查询”表现不佳。所以我认为“左连接查询”会表现得更好但事实并非如此。我在VBA中运行这些查询。

这是我的“不存在的查询”

SELECT * FROM MyTable AS t1
WHERE t1.ID_person = 1960081947465
and t1.ID_company <> 68550
and t1.FullTime + 26.3 >= 37.33 
and t1.Date <= 20130101
and t1.Code not in (31,28) 
and t1.FullTime < 100          
and not exists (
                  select * from MyTable t2 where 
                  t1.ID_person = t2.ID_person 
                  and t2.ID_company <> 68550
                  and t2.FullTime + 26.3 >= 37.33 
                  and t2.Date <= 20130101 
                  and t2.Code not in (31,28) 
                   and t1.Date< t2.Date 
                 ) 

以下是我试图获得相同结果但使用“左连接查询”

的方式
SELECT * FROM MyTable AS t1
LEFT JOIN
(
 select * from MyTable t2 where
 and t2.ID_company <> 68550
 and t2.FullTime + 26.3 >= 37.33
 and t2.Date <= 20130101
 and t2.Code not in (31,28)
 ) subq
 ON t1.ID_person = subq.ID_person and t1.Date < subq.Date 
 WHERE t1.ID_person = 1960081947465
 and t1.ID_company <> 68550
 and t1.FullTime + 26.3 >= 37.33
 and t1.Date <= 20130101
 and t1.Code not in (31,28)
 and t1.FullTime < 100          
 and subq.ID_person IS NULL

为什么“左连接查询”表现较差?我以为它会更快。我有相同查询的第三个版本,但使用“不在”。该查询非常类似于“不存在的查询”,我认为我不需要在此处发布它。

任何人都可以提出更好/更快的“左连接查询”???

1 个答案:

答案 0 :(得分:0)

我要说你需要参与所有列的索引,这些列参与了where子句中出现的以相同顺序的join / where子句。确保您拥有相应的索引,not existsjoin的执行速度应相同且快速。