简体   繁体   English

在 where 原因中使用交叉应用列时查询很慢

[英]Query is Slow when using cross apply column in where cause

This is my query.这是我的查询。 Every row in tblSMSSendQueueMain may have some record in tblSMSSendQueueMainSendStatus. tblSMSSendQueueMain 中的每一行都可能在 tblSMSSendQueueMainSendStatus 中有一些记录。 QueueID in tblSMSSendQueueMainSendStatus is foreign key for ID in tblSMSSendQueueMain tblSMSSendQueueMainSendStatus 中的 QueueID 是 tblSMSSendQueueMain 中 ID 的外键

select top 10 ID from tblSMSSendQueueMain q
CROSS Apply
(
    select top 1 SendStatus from tblSMSSendQueueMainSendStatus where QueueID = q.ID order by ID desc
) qs
where qs.SendStatus = 1 order by ID Desc

This query take a long time to run.此查询需要很长时间才能运行。 But if I write qs.SendStatus = 5 its fast.但是如果我写qs.SendStatus = 5它很快。

I have nonclustered index on tblSMSSendQueueMainSendStatus as below我在 tblSMSSendQueueMainSendStatus 上有非聚集索引,如下所示

CREATE NONCLUSTERED INDEX [IX_tblSMSSendQueueMainSendStatus_SendStatus] ON [dbo].[tblSMSSendQueueMainSendStatus]
(
    [QueueID] ASC,
    [ID] DESC
)
INCLUDE([SendStatus]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

Whats wrong?怎么了? Or is there is a better way to write this query, joining multi tables values and filter the result.或者是否有更好的方法来编写此查询,连接多个表值并过滤结果。

Thanks谢谢

As I don't have your execution plans.因为我没有你的执行计划。 I am just providing an alternative way of INNER JOIN.我只是提供了另一种 INNER JOIN 方式。 Test your query for performance.测试查询的性能。

;WITH CTE_QueueStatus AS
(
select q.ID, qs.SendStatus, ROW_NUMBER() OVER(PARTITION BY qs.QueueID ORDER BY qs.ID desc)  as rnk from tblSMSSendQueueMain q
INNER JOIN tblSMSSendQueueMainSendStatus qs ON  qs.QueueID = q.ID
)
SELECT top 10 ID 
FROM CTE_QueueStatus AS c
where qs.SendStatus = 1 -- only sendstatus =1 is selected
and c.rnk = 1 -- Only the top status is selected
order by ID Desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM