【问题标题】:Outer apply takes a long time when it contains string compare in it外部应用在其中包含字符串比较时需要很长时间
【发布时间】:2019-02-27 13:16:40
【问题描述】:

我有一个问题:

with cte as
(   
//some select statement
)
    select -
    // also some code here
     from cte a 
     outer apply
(select top 1 position,traffic,tags,url,Domain,Load_Date,trend_date
    from cte b 
    where b.Date_ID<=a.Date_ID and 
        b.Load_Date is not null and 
        a.Domain is null and 
        a.Project_Id=b.Project_Id and
        a.SE_Id=b.SE_Id  and
        a.Keyword=b.keyword 
        order by a.Date_ID desc
        )x

我的cte 返回近 300 万行。此查询需要很长时间才能完成(每 4 分钟只返回 500 行)

但是在外部应用中没有Keyword比较的以下查询非常快:

with cte as
(   
//some select statement
)
    select 
    // also some code here
     from cte a 
     outer apply
(select top 1 position,traffic,tags,url,Domain,Load_Date,trend_date
    from cte b 
    where b.Date_ID<=a.Date_ID and 
        b.Load_Date is not null and 
        a.Domain is null and 
        a.Project_Id=b.Project_Id and
        a.SE_Id=b.SE_Id  and
        order by a.Date_ID desc
        )x

问题是,我需要在查询中进行此关键字比较。我现在的问题是,我应该如何更改原始查询以获得更好的性能? 很高兴知道:

  • Project_Id 是int
  • SE_Id 是int
  • 关键字是nvarchar(2000)

【问题讨论】:

  • 您必须检查执行计划。在所有的可能性。第一个允许使用索引。
  • 什么是“Mio”?
  • @Larnu Milion
  • 我建议您尝试将数据加载到临时表中,而不是在这种情况下使用 cte。
  • @DenisRubashkin 我已经测试过了,但性能变化不大

标签: sql sql-server tsql outer-apply


【解决方案1】:

在第二个查询使用的索引中包含Keyword

【讨论】:

    猜你喜欢
    • 2022-06-20
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    相关资源
    最近更新 更多