加入两个 table,其中一个 table 与多个 table 有关系

Join two table where one table has relation with many table

我有5个table,结构如下--

user - id
     - name
     - dob
     - phone

desi - id
     - desgname
     - dept_id

dept - id
     - deptname
     - org_id

org  - id
     - orgname

junction_table    - id
                  - userid
                  - desg_id
                  - dept_id
                  - org_id

我怎样才能联合起来table?

更新

经过一段时间的尝试,我找到了解决方案并将其发布为答案

试试这个

    $this->db->select('your-selection');
    $this->db->from('user');
    $this->db->join('designation','user.designation_id=designation.designation_id');
    $this->db->join('department','user.department_id=department.department_id');
    $this->db->join('org','user.org_id=org.org_id');
    $this->db->join('designation','user.designation_id=designation.designation_id');
    $this->db->where('your-condition`);
    $result_set = $this->db->get();
    return $result_set->result();

your-selection 可以是您想要 select.

的字段

your-condition可以是你的条件数组。

如果我理解得很好,我认为你需要这样的东西,加入每个 table 以获取你需要的信息。

SELECT
    U.name
    ,D.desgname
    ,DPT.deptname
    ,O.orgname
FROM junction_table JT
INNER JOIN [user] U
    ON JT.userid = U.id
INNER JOIN [desi] D
    ON JT.desg_id = D.id
INNER JOIN [dept] DPT
    ON JT.dept_id = DPT.id
INNER JOIN org O
    ON JT.org_id = O.id

解决方案是将联结 table 左联到用户 table,然后再左联到联结 table 到其他 table

SELECT
U.name,
O.orgname,
DPT.dpt,
D.desgname
FROM user U
LEFT JOIN junction_table JT
    ON U.id = JT.user_id
LEFT JOIN organization O
    ON JT.org_id = O.id
LEFT JOIN tbl_suborg DPT
    ON JT.dpt_id = DPT.id
LEFT JOIN designation D
    ON JT.desg_id = D.id

感谢兄弟的帮助。