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

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

    The highest voted answer does not seem correct to me, and seems overcomplicated. Just group by the code field on table B in your subquery and select the maximum Id per grouping.

    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 IN
                (SELECT MAX(field_that_is_unique)
                 FROM table_b
                 GROUP BY table_b.code)
    
    0 讨论(0)
提交回复
热议问题