[英]SQL Server : why is this query so slow?
我有一條SQL語句來提取記錄。 某些員工可以訪問某些記錄。 人員安全都在一個單獨的過程中完成,並附加到搜索SQL子句的where子句中。
簡化示例:
select
o.id, o.staff.id
from
Orders o
where
staffid = 100
or orderid in (select orderid from schedule where staffid = 5)
與
select
o.id, o.staff.id
from
Orders o
where
staffid = 100 or orderid in (1, 2, 3, 4, 5, 6, 7, 8)
select orderid from schedule where teamid = 5
嵌套的sql select orderid from schedule where teamid = 5
在1秒內運行。 如果將結果粘貼到其位置,則主查詢將在2秒鍾內運行。 如果運行頂級SQL,則將花費一分鍾以上的時間。 出於某種原因,如何告訴SQL先運行嵌套選擇而不將其拆分到臨時表中?
您所有建議中的更多信息:
我的SQL還僅具有OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
。 刪除后,查詢速度很快。 它可以在1秒鍾內返回1800條記錄,但是要求10條記錄則需要40秒鍾。
如果我將訂單更改為staffid
它的運行速度也會很快。 接下來的order by
和fetch next
的組合使SQL運行不同的執行計划。 由於Where
子句位於軟件的單獨部分中,並且我無法通過更改order by
,因此這會降低性能。
with scheduleOrders as
(select orderid from schedule where staffid = 5)
select o.id, o.staff.id
from Orders o
where o.staffId = 100
union
select o.id, o.staff.id
from Orders o join scheduleOrders so on o.orderId = so.orderId
SELECT o.id, o.staffId
FROM Orders o
WHERE o.staffid = 100
OR EXISTS ( SELECT 'a'
FROM schedule s
WHERE s.staffId = 5
AND s.orderId = o.orderId
)
編輯...加入版本更快嗎?
SELECT DISTINCT o.*
FROM Orders o JOIN schedule s ON s.orderId = o.orderId
WHERE o.staffid = 100
OR s.staffId = 5
您的表有幾行?
嘗試使用Exists
Select o.id, o.staff.id
from Orders o
Where staffid = 100 or EXISTS (select 1 from schedule s where staffid = 5 and s.orderid=o.orderid)
使用In
會嘗試檢索所有內部查詢結果,而使用Exists
只會檢查行是否存在
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.