2017-06-29 179 views
-4

我有一個選擇查詢,我需要改進才能使其更快。SQL查詢非常慢,需要改進

SELECT 
    st.SigHistUID, st.RelationType, st2.RelationType, 
    case 
     when st.RelationType <> st2.RelationType 
      then 'N' 
      else st.RelationType 
    end as [NewRelationType], 
    st.ToSigUID , sh.FullDescription, sh.SigHistUID AS ToSigHistUID 
FROM 
    [Stackability] (nolock) st 
INNER JOIN 
    [SignatureHistory] (nolock) sh ON sh.SigUID = st.ToSigUID 
            AND sh.SigHistUID = (SELECT TOP 1 SigHistUID FROM [SignatureHistory] (nolock) tmp where tmp.SigUID = sh.SigUID ORDER BY SigHistUID DESC) 
INNER JOIN 
    [SignatureHistory] (nolock) sh2 ON st.SigHistUID = sh2.SigHistUID 
INNER JOIN 
    Stackability (nolock) st2 on st2.ToSigUID = sh2.SigUID and st2.SigHistUID = sh.SigHistUID 
WHERE 
    st.SigHistUID < 1000 and 
    st.RelationType <> st2.RelationType 
ORDER BY 
    st.SigHistUID 
+8

這是**得太少**信息!什麼是桌子結構?這些表上定義了什麼樣的索引?每張桌子都有哪些數據(以**爲單位)? –

+4

你應該[至少包括實際的執行計劃](https://stackoverflow.com/a/7359705/1260204),你可以使用[粘貼計劃](https://www.brentozar.com/pastetheplan /)並在你的問題中分享鏈接。另外[嘗試自己讀](https://stackoverflow.com/a/759097/1260204),也許你可以找出與您的查詢性能問題(S)。最後,包括[schema ddl](https://en.wikipedia.org/wiki/Data_definition_language)以及您正在執行的查詢。 – Igor

+0

根據SignatureHistory的大小,由於子查詢結果未被編入索引,子查詢可能會在sh連接上減慢速度。也許找到一種方法來避免該子查詢。 – justiceorjustus

回答

0

嘗試有取出頂部1條件:

SELECT 
    st.SigHistUID, st.RelationType, st2.RelationType, 
    case 
     when st.RelationType <> st2.RelationType 
      then 'N' 
      else st.RelationType 
    end as [NewRelationType], 
    st.ToSigUID , sh.FullDescription, sh.SigHistUID AS ToSigHistUID 
FROM 
    [Stackability] (nolock) st 
INNER JOIN 
    (select distinct siguid, max(SigHistUID) OVER(PARTITION BY siguid) as SigHistUID from [SignatureHistory] (nolock)) sh ON sh.SigUID = st.ToSigUID 

INNER JOIN 
    [SignatureHistory] (nolock) sh2 ON st.SigHistUID = sh2.SigHistUID 
INNER JOIN 
    Stackability (nolock) st2 on st2.ToSigUID = sh2.SigUID and st2.SigHistUID = sh.SigHistUID 
WHERE 
    st.SigHistUID < 1000 and 
    st.RelationType <> st2.RelationType 
ORDER BY 
    st.SigHistUID 
+0

非常感謝大家。 –