如何在MySQL中加入分层表(表连接其他表连接其他表的其他表)?

时间:2017-06-26 10:53:37

标签: php mysql

我有3个表,tb_item,tb_branch,tb_department,tb_division。

database design

如你所见:

  • tb_division属于tb_department
  • tb_department正在分支
  • tb_branch没有上级

例如,如果我想检索item_id 1或2或3,那么这应该是结果

desired result

如果我想检索item_id 2,那么它将显示部门和分支。 我的问题是,如果我知道该项与特定表相关,我可以嵌套加入它们但在这种情况下,因为tb_item可以与tb_division或tb_department和tb_branch相关我不知道应该查询什么查询配制

由于此设计已经实施,因此无法更改数据库设计。

2 个答案:

答案 0 :(得分:0)

SELECT column-names
  FROM table-name1 JOIN table-name2 
    ON column-name1 = column-name2
 WHERE condition

答案 1 :(得分:0)

别介意人。我设法自己解决了。因为我认为我需要做大量的子查询而一直在努力。谢谢你的答案。

SELECT
   i.item_id,
   dv.division_name,
   COALESCE(dept.department_name, dept2.department_name) AS department_name,
   COALESCE(br.branch_name, br2.branch_name, br3.branch_name) AS branch_name 
FROM
   tb_item AS i 
   LEFT JOIN
      tb_division AS dv 
      ON i.division_id = dv.division_id 
   LEFT JOIN
      tb_department AS dept2 
      ON dv.department_id = dept2.department_id 
   LEFT JOIN
      tb_branch AS br2 
      ON dept2.branch_id = br2.branch_id 
   LEFT JOIN
      tb_department AS dept 
      ON i.department_id = dept.department_id 
   LEFT JOIN
      tb_branch AS br3 
      ON dept.branch_id = br3.branch_id 
   LEFT JOIN
      tb_branch AS br 
      ON i.branch_id = br.branch_id