Select first record in a One-to-Many relation using left join

后端 未结 7 1280
予麋鹿
予麋鹿 2020-12-02 16:52

I\'m trying to join two tables using a left-join. And the result set has to include only the first record from the \"right\" joined table.

Lets say I have two tables

7条回答
  •  余生分开走
    2020-12-02 17:37

    Another option: OUTER APPLY

    If supported by the database, OUTER APPLY is an efficient and terse option.

    SELECT *
    FROM 
        Table_A a
    OUTER APPLY
        (SELECT TOP 1 * 
        FROM Table_B b_1
        WHERE b_1.code = a.code
        ) b
    ;
    

    This results in a left join to the indeterminate first matched record. My tests show it to be quicker than any other posted solution (on MS SQL Server 2012).

提交回复
热议问题