Left Join without duplicate rows from left table

前端 未结 3 901
夕颜
夕颜 2020-12-02 09:59

Please look at the following query:

tbl_Contents

Content_Id  Content_Title    Content_Text
10002   New case Study   New case Study
1         


        
3条回答
  •  不思量自难忘°
    2020-12-02 10:11

    Try an OUTER APPLY

    SELECT 
        C.Content_ID,
        C.Content_Title,
        C.Content_DatePublished,
        M.Media_Id
    FROM 
        tbl_Contents C
        OUTER APPLY
        (
            SELECT TOP 1 *
            FROM tbl_Media M 
            WHERE M.Content_Id = C.Content_Id 
        ) m
    ORDER BY 
        C.Content_DatePublished ASC
    

    Alternatively, you could GROUP BY the results

    SELECT 
        C.Content_ID,
        C.Content_Title,
        C.Content_DatePublished,
        M.Media_Id
    FROM 
        tbl_Contents C
        LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
    GROUP BY
        C.Content_ID,
        C.Content_Title,
        C.Content_DatePublished,
        M.Media_Id
    ORDER BY
        C.Content_DatePublished ASC
    

    The OUTER APPLY selects a single row (or none) that matches each row from the left table.

    The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

提交回复
热议问题