【问题标题】:SQL - Optimize the execution timeSQL - 优化执行时间
【发布时间】:2017-11-16 04:47:48
【问题描述】:

我正在尝试从 stackexchange 数据库中获取数据。我的查询是:

select distinct top 50 U.Id, U.DisplayName, U.Reputation,
       Tags = stuff( (SELECT ','+p2.Tags 
                       FROM posts p2 join votes V on p2.id = V.PostId
                       where V.VoteTypeId=5 and V.UserId = U.id
                       order by p2.CreationDate DESC
                       FOR XML PATH, TYPE).value('.[1]','nvarchar(max)')
                    ,1,1,'')
from Users U 
order by U.Reputation DESC;

但是,当我在 data.stackexchange.com 上运行查询时,它显示错误消息:Execution Timeout Expired. 有什么方法可以修改查询以优化执行时间,以便我可以成功运行此查询?

【问题讨论】:

  • 在这里brentozar.com/pastetheplan发布执行计划并在问题中分享。同时添加index 详细信息
  • 我没有数据库中的离线数据我不知道如何通过stackexchange数据库在线获取执行计划,你能告诉我怎么做吗? @Pரதீப்

标签: sql sql-server data.stackexchange.com


【解决方案1】:

您需要排除带有单个 XML 的子查询。这将需要构建具有结构<user ...><tag1><tag2>...</user><user>... 的通用XML(使用EXPLICIT MODE)。并将其解析为单个用户的行。

with U as(
    select top 50 id, Reputation, DisplayName
      from users order by Reputation DESC
),
V as(
 select U.*,p2.Tags, p2.CreationDate
  from U, posts p2, votes V
 where p2.id = V.PostId and V.VoteTypeId=5 and V.UserId = U.id
),
Q(XML) as(
    select tag,parent,id [user!1!id],Reputation [user!1!Reputation],Name [user!1!Name], T [T!2!!element]
      from (
        select 1 tag, NULL parent, U.id, U.Reputation, U.DisplayName Name, NULL t, NULL dt
          from U
         union all
        select 2, 1, V.id, NULL, NULL, ','+Tags, CreationDate
          from V
     ) X
     order by id, tag, dt desc
       for xml explicit, type
)
select node.value('(@id)[1]','int'),
       node.value('(@Reputation)[1]','int'),
       node.value('(@Name)[1]','nvarchar(max)'),
       stuff(node.value('.[1]','nvarchar(max)'),1,1,'')
  from Q
 cross apply XML.nodes('/user') as Y(node)
 order by 2 desc

【讨论】:

  • 谢谢!有用!但是当我尝试检索top 5000 时,可能会出现预期超时的情况。你能帮我检索前 5000 行吗?
  • @LeoLi 前 5000 名用户有 50 万个声音,这太多了,卸载不掉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多