【问题标题】:Optimize short part of a SQL Server query优化 SQL Server 查询的一小部分
【发布时间】:2017-08-17 02:46:40
【问题描述】:

我有这个需要很长时间的子查询。有谁知道如何修改它以便更快?

  ISNULL(ISNULL(
(select top 1 CONVERT(VARCHAR(11), qq.startdate , 111) 
 from (select a.startdate, a.ownerid 
       from wfassignment a
       where a.ownertable='PM' /*order by a.startdate*/)qq 
 where qq.ownerid=pm.pmuid ),
(select min(w.reportdate) 
from workorder w where w.pmnum=pm.pmnum 
                 and w.siteid=pm.siteid 
                 and w.orgid= pm.orgid)
),CONVERT(DATETIME,'01-02-2015 00:00:00'))

在 oracle 中它比在 SQL Server 中快得多。我还想确定 top 1 是否与 oracle 的 rownum=1 等价。 谢谢:)

【问题讨论】:

  • 寻求性能帮助的问题,应包括执行计划、涉及的表架构和要测试的重现等详细信息:support.microsoft.com/en-us/help/914288/…
  • 多个需求最终可能会产生具有相同结构的查询——而不是期望直觉这个查询背后的意图,你能否解释一下 .样本数据和预期结果会有很大帮助。
  • 在 Oracle 中并不快。这是一个完全不同的查询,在一个完全不同的数据库上,具有不同的索引。如果索引不同,则查询的文本形状无关紧要。

标签: sql-server min isnull


【解决方案1】:

我假设您在第一个子查询中需要最小开始日期,所以我计算出了这个:

    select   top 1 [sq].[pm_date]
    from
    (
        select  convert(tinyint, 1) as [priority]
              , min(a.startdate) as [pm_date]
        from    wfassignment a
        where   a.ownertable = 'PM'
                and a.ownerid = pm.pmuid

        union all

        select  2
              , min(w.reportdate)
        from    workorder w
        where   w.pmnum = pm.pmnum
                and w.siteid = pm.siteid
                and w.orgid = pm.orgid

        union all

        select  3
              , convert(datetime, '2015-02-01 00:00:00') 
              /* use yyyymmdd format to avoid confusion when casting datetime values */
    ) as sq
    where    [sq].[pm_date] is not null
    order by [sq].[priority] asc

您需要添加对 [pm] 别名的外部引用,但您的问题中没有给出该部分,所以我只是这样解决。

【讨论】:

    猜你喜欢
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多