【问题标题】:Improve SQL select query execution time改进 SQL 选择查询执行时间
【发布时间】:2018-10-01 04:15:36
【问题描述】:

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

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

tblPaymentGatewayLog 只有 10 条记录,但tblentityList 可以有超过 20000 条记录,因此查询速度很慢。

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

【问题讨论】:

  • 执行计划揭示了什么?
  • 你能提供DDL连同所有索引吗?

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


【解决方案1】:
select distinct payment_gateway_id 
from tblPaymentGatewayLog pgl
where exists (select 1 from tblentityList el where el.entity_id = pgl.entity_id)

【讨论】:

    【解决方案2】:

    我也是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 太小了,我认为索引不会有帮助。

    【讨论】:

      【解决方案3】:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        • 2020-04-22
        • 2019-04-16
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        相关资源
        最近更新 更多