CREATE TABLE department ( department_id NUMBER PRIMARY KEY, parent_id NUMBER, department_name VARCHAR(250) NOT NULL ); select * from department for update drop table department 该公司总共有三个层级,请用SQL查询出公司的组织架构情况,结果输出三个字段:一级部门名称、二级部门名称、三级部门名称
时间: 2024-03-31 14:37:19 浏览: 52
可以使用递归查询语句来查询公司的组织架构情况,以下是示例代码:
WITH RECURSIVE dept_tree AS (
SELECT department_id, parent_id, department_name, department_name AS full_path
FROM department
WHERE parent_id IS NULL
UNION ALL
SELECT d.department_id, d.parent_id, d.department_name, CONCAT(dt.full_path, ' > ', d.department_name)
FROM department d
JOIN dept_tree dt ON dt.department_id = d.parent_id
)
SELECT
CASE WHEN d1.department_name IS NULL THEN 'N/A' ELSE d1.department_name END AS level1,
CASE WHEN d2.department_name IS NULL THEN 'N/A' ELSE d2.department_name END AS level2,
CASE WHEN d3.department_name IS NULL THEN 'N/A' ELSE d3.department_name END AS level3
FROM dept_tree dt
LEFT JOIN dept_tree d1 ON dt.parent_id = d1.department_id
LEFT JOIN dept_tree d2 ON dt.parent_id = d2.parent_id AND d2.parent_id IS NOT NULL AND d1.department_id = d2.parent_id
LEFT JOIN dept_tree d3 ON dt.parent_id = d3.parent_id AND d3.parent_id IS NOT NULL AND d2.department_id = d3.parent_id
WHERE dt.parent_id IS NOT NULL
ORDER BY level1, level2, level3;
解释一下上述代码的逻辑:
- 使用 WITH RECURSIVE 定义一个递归查询语句 dept_tree,首先查询出所有 parent_id 为空的部门作为第一级部门;
- 然后使用 UNION ALL 连接查询,将每个部门的子部门递归查询出来,同时使用 CONCAT 函数将每个部门的完整路径记录下来;
- 最后使用 LEFT JOIN 将每个部门与其父部门和祖父部门(如果有的话)连接起来,查询出每个部门所属的三个级别,如果没有对应的级别则用 'N/A' 表示。
注意:上述代码中的 SELECT * from department for update drop table department 是错误的 SQL 语句,不要在实际场景中使用!
阅读全文