我有以下SQL查询,该查询引发数据库超时错误。
select distinct payment_gateway_id
from tblPaymentGatewayLog
where entity_id in (select entity_id from tblentityList)
tblPaymentGatewayLog
仅具有10条记录,但是tblentityList
可以包含20000条记录,因此查询速度很慢。
我尝试使用内部联接而不是IN查询,但是仍然没有区别。有什么方法可以缩短查询执行时间?
答案 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)