我有一个SQL查询:
select person from table t1
inner join person_history ph
on t1.person = ph.person
and t1.person not in (select person from person_history
where effective_date < '01-01-2013')
and ph.person.effective_date > '01-01-2013'
由于person_history
包含大量记录,因此此查询耗时太长。
如何优化此代码?
答案 0 :(得分:1)
你不能只做这样的事情:
select person from table t1
inner join person_history ph
on t1.person = ph.person
where ph.effective_date >= '01-01-2013'
答案 1 :(得分:1)
您无需排除NOT IN,因为它已在WHERE过滤器中排除! SQL将很简单,如下所示:
select person from table t1
inner join person_history ph on t1.person=ph.person
where effective_date > '01-01-2013'
或者:
select person from table t1
WHERE person IN(select ph.person from person_history ph
where effective_date > '01-01-2013' and t1.person=ph.person)