2015-02-05 74 views
1

我有兩個表,並在下面的查詢優化。 我想要同一行小照片和大照片欄。如何優化這個sql查詢並縮短?

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:

+0

你能告訴我們更多關於你正在查詢的表格? – kittykittybangbang 2015-02-05 14:58:50

回答

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;