Left Join without duplicate rows from left table

前端 未结 3 889
夕颜
夕颜 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.

    0 讨论(0)
  • 2020-12-02 10:28

    You can do this using generic SQL with group by:

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

    Or with a correlated subquery:

    SELECT C.Content_ID, C.Contt_Title,
           (SELECT M.Media_Id
            FROM tbl_Media M
            WHERE M.Content_Id = C.Content_Id
            ORDER BY M.MEDIA_ID DESC
            LIMIT 1
           ) as Media_Id
    FROM tbl_Contents C 
    ORDER BY C.Content_DatePublished ASC;
    

    Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

    0 讨论(0)
  • 2020-12-02 10:29

    Using the DISTINCT flag will remove duplicate rows.

    SELECT DISTINCT
    C.Content_ID,
    C.Content_Title,
    M.Media_Id
    
    FROM tbl_Contents C
    LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
    ORDER BY C.Content_DatePublished ASC
    
    0 讨论(0)
提交回复
热议问题