如何优化这个sql查询并缩短?

时间:2015-02-05 14:54:54

标签: sql sql-server tsql

我有两个表,想要优化下面的查询。 我想要同样的小照片和大照片列。

    Table Projects

    ProjectID | ProjectName | ProjectContent
    ----------------------------------------
       2      | Test        | Test

    Table Media



    RID | MediaTypeID | FilePathAndName  | ProjectID
    ------------------------------------------------
    1   |      1      | big_photo.jpeg   |    2
    2   |      2      | small_photo.jpeg |    2



    SELECT
        T1.ProjectID,
        T1.ProjectName,
        T1.ProjectContent,
        T1.FilePathAndName AS BigPhoto,
        T2.FilePathAndName AS SmallPhoto
    FROM
    (
        SELECT 
            P.ProjectID,
            P.ProjectName,
            P.ProjectContent,
            M.FilePathAndName,
            ROW_NUMBER() over(ORDER BY M.RID) AS RN             
        FROM 
            Projects (NOLOCK) AS P
            INNER JOIN Media (NOLOCK) AS M ON M.RID = P.ProjectID AND M.MediaType = 1       
        WHERE
            P.ProjectID = 2
    ) AS T1,
    (       
        SELECT 
            P.ProjectID,
            P.ProjectName,
            P.ProjectContent,
            M.FilePathAndName,
            ROW_NUMBER() over(ORDER BY M.RID) AS RN             
        FROM 
            Projects (NOLOCK) AS P
            INNER JOIN Media (NOLOCK) AS M ON M.RID = P.ProjectID AND M.MediaType = 2       
        WHERE
            P.ProjectID = 2
    ) AS T2
    WHERE 
        T1.RN = T2.RN

结果 Result:

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的代码,我认为您不需要加入,也不需要ROW_NUMBER

SELECT 
    P.ProjectID,
    P.ProjectName,
    P.ProjectContent,
    MIN(CASE WHEN  M.MediaType = 1 THEN M.FilePathAndName END) AS BigPhoto,
    MIN(CASE WHEN  M.MediaType = 2 THEN M.FilePathAndName END) AS SmallPhoto
FROM 
    Projects (NOLOCK) AS P
    INNER JOIN Media (NOLOCK) AS M ON M.RID = P.ProjectID       
WHERE
     M.MediaType IN (1,2) AND P.ProjectID = 2
GROUP BY 
    P.ProjectID,
    P.ProjectName,
    P.ProjectContent;