SQL:如何加入分层表关系

时间:2017-05-26 08:39:21

标签: mysql sql join

我有3个表DepartmentOfficeDivision

假设流程是:Department has Offices has Divisions

但有些情况Divisions直接向Departments

报告

示例数据

Department   Office                Division
[id][name]   [dept_id][id][name]   [dept_id][off_id][id][name]
[ 1][A   ]   [     1 ][ 1][D   ]   [     1 ][    2 ][ 1][G   ]
[ 2][B   ]   [     1 ][ 2][E   ]   [     3 ][ NULL ][ 2][H   ]
[ 3][C   ]   [     3 ][ 3][F   ]   [     3 ][   3  ][ 3][I   ]

所需输出以显示所有分部

OUTPUT
[AS dept_name][AS off_name][AS div_name]
[      A     ][     E     ][     G     ]
[      C     ][    NULL   ][     H     ]
[      C     ][     F     ][     I     ]

我目前的查询是:

    SELECT * FROM `Division` A 
    RIGHT JOIN `Office` B ON A.`off_id` = B.`id` 
    RIGHT JOIN `Department` C ON A.`dept_id` = C.`id`;

我的查询错误,所以我正在寻找一种方法来加入这3个表来实现所需的输出

1 个答案:

答案 0 :(得分:1)

如果您想显示所有部门,则必须使用LEFT JOIN

SELECT
  Department.`name` AS dept_name, 
  Office.`name` AS off_name,
  Division.`name` AS div_name
FROM
  Division 
  LEFT JOIN Office ON Division.off_id = Office.id
  LEFT JOIN Department ON Division`.dept_id = Department.id;