How to get multiple records against one record based on relation?

前端 未结 8 809
遇见更好的自我
遇见更好的自我 2020-11-29 09:11

I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particula

8条回答
  •  温柔的废话
    2020-11-29 09:20

    Here's what you can do, you have 2 options:

    select *
    FROM
      users u
      LEFT JOIN organizations o ON (u.idorg = o.id);
    

    This way you will get extra data on each row - full organization info you don't really need.

    Or you can do:

    select o.*, group_concat(u.name)
    FROM
      users u
      LEFT JOIN organizations o ON (u.idorg = o.id)
    GROUP BY
      o.id
    

    http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

    The second approach is applicable if you want to see ie. list of usernames "user1, user2, user3", but don't want to operate on the fields themselves...

提交回复
热议问题