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

后端 未结 7 1264
予麋鹿
予麋鹿 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:33

    After playing around a bit, this turns out to be trickier than I'd expected! Assuming that table_b has some single column that is unique (say, a single-field primary key), it looks like you can do this:

    SELECT table_a.code,
           table_a.emp_no,
           table_b.city,
           table_b.county
      FROM table_a
      LEFT
      JOIN table_b
        ON table_b.code = table_a.code
       AND table_b.field_that_is_unique =
            ( SELECT TOP 1
                     field_that_is_unique
                FROM table_b
               WHERE table_b.code = table_a.code
           )
    ;
    

提交回复
热议问题