缩短SQL选择查询的执行时间

时间:2018-10-01 04:15:36

标签: sql sql-server sql-server-2008-r2

我有以下SQL查询,该查询引发数据库超时错误。

select distinct payment_gateway_id 
from tblPaymentGatewayLog 
where entity_id in (select entity_id from tblentityList)

tblPaymentGatewayLog仅具有10条记录,但是tblentityList可以包含20000条记录,因此查询速度很慢。

我尝试使用内部联接而不是IN查询,但是仍然没有区别。有什么方法可以缩短查询执行时间?

3 个答案:

答案 0 :(得分:2)

select distinct payment_gateway_id 
from tblPaymentGatewayLog pgl
where exists (select 1 from tblentityList el where el.entity_id = pgl.entity_id)

答案 1 :(得分:1)

我也是exists的粉丝:

select distinct gl.payment_gateway_id 
from tblPaymentGatewayLog gl
where exists (select 1 from tblentityList el where el.entity_id  = gl.entity_id);

由于select distinct,这仍然很棘手。因此,我还建议在(tblPaymentGatewayLog, entity_id)上建立索引。 tblentityList太小,我认为索引没有帮助。

答案 2 :(得分:0)

Exists的速度比IN快,并且join将返回重复的记录。

我的偏好是Exists

select distinct payment_gateway_id 
from tblPaymentGatewayLog T1
where exists (select 1 from tblentityList T2 where T2.entity_id = T1.entity_id)