简体   繁体   中英

How to join hierarchical table in MySQL (table joins other table that joins other table that joins other table)?

I have 3 tables, tb_item, tb_branch, tb_department, tb_division.

数据库设计

As you can see:

  • tb_division is under tb_department
  • tb_department is under branch
  • tb_branch has no superior

for example if I want to retrieve item_id 1 or 2 or 3 then this should be the result

理想的结果

If I want to retrieve item_id 2 then it will show the department and branch. My problem is that I can nested join them if if I know the item is related to a specific table but in this case since tb_item can be related to tb_division or tb_department and tb_branch I don't know what query should I formulate .

Changing the database design is not an option since this design is already implemented.

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

Never Mind guys. I managed to solved it myself. been struggling since I thought I need to do tons of subqueries. Thanks for the answers tho.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM