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

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

    I modified the answer from ruakh and this seem to work perfectly with mysql.

    SELECT 
       table_a.code,
       table_a.emp_no,
       table_b.city,
       table_b.county
    FROM table_a a
    LEFT JOIN table_b b
    ON b.code = a.code 
    AND b.id = (  SELECT id FROM table_b 
                  WHERE table_b.code = table_a.code 
                  LIMIT 1
               )
    ;
    

提交回复
热议问题