有一张大表T1和一个比较复杂的视图V1
写了个sql语句
select
...
from T1 as t1
where not exists
(
select
...
from V1 as v1
where t1.key1=v1.key1 and t1.key2=v1.key2 and t1.key3=v1.key3
)
T1和V1有相同的key,想查找T1中不在V1中的那些数据。
如果就这么执行,速度很快,几秒钟的样子,
但是一旦加上带or的where条件
比如加上
and
(t1.key1=... and t1.key2>=...)
or
(t1.key1=... and t1.key2<=...)
执行起来特别慢
如果我把or去掉分别执行,就比较快,或者加个括号
and
(
(t1.key1=... and t1.key2>=...)
or
(t1.key1=... and t1.key2<=...)
)
也很快。
请问各位,这是为什么,是不是跟我写的那个复杂的视图有关。where条件里面加个or特别影响速度。
------解决思路----------------------
帮你移动过来了
oracle的话是把or改为union或union all的形式,ms-sql应该大同小异吧
select * from T WHERE 条件1
union all
select * from T WHERE 条件2
------解决思路----------------------
把Or的部份拆解成两个SQL语句,然后用Union All 将结果集合并在一起。
如:
select
...
from T1 as t1
where not exists
(
select
...
from V1 as v1
where (t1.key1=... and t1.key2>=...)
)
Union All
select
...
from T1 as t1
where not exists
(
select
...
from V1 as v1
where (t1.key1=... and t1.key2<=...)
)
)
------解决思路----------------------
撸主
别or了,使用动态sql试试?
or比较慢的话,看看执行计划。
另外视图也是可以创建索引的嘛