SQL查询非常慢,需要进行改进

时间:2017-06-29 15:24:47

标签: sql sql-server

我有一个我需要改进的选择查询,以使其快速。

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

1 个答案:

答案 0 :(得分: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