如何验证企业层级结构仅存在两级?
企业层级数据表
| 公司名称 | Parent_ID | Company_ID |
|---|---|---|
| ABC | NULL | 1 |
| ABC子公司 | 1 | 2 |
| ABC子公司2 | 1 | 3 |
| ABC子公司3 | 1 | 4 |
| ABC子公司4 | 1 | 5 |
| DEF | NULL | 6 |
| DEF子公司 | 6 | 7 |
| DEF子公司2 | 6 | 8 |
| DEF子公司3 | 6 | 9 |
| GHI | NULL | 10 |
| GHI子公司 | 10 | 11 |
已知层级规则
- 父公司的
Parent_ID为NULL - 子公司的
Parent_ID等于对应父公司的Company_ID
示例:ABC公司的
Parent_ID为NULL,属于父公司;所有ABC子公司的Parent_ID均为1,即ABC的Company_ID
需求
验证该层级结构仅存在两级,确认不存在隶属于其他子公司的子公司(即没有子公司的父级为非父公司)。
现有尝试的SQL语句
之前尝试的语句只能查出所有父公司,无法验证层级深度:
select * from table1 where Parent_ID is null
解决方案
要验证是否存在三级及以上层级,核心是检查是否有公司的Parent_ID对应的Company_ID本身是子公司(即该Parent_ID对应的公司的Parent_ID不为NULL)。
方法1:查询违规数据
通过关联查询直接找出所有父级为子公司的记录(这类记录的存在意味着层级超过两级):
select child.* from table1 child join table1 parent on child.Parent_ID = parent.Company_ID where parent.Parent_ID is not null;
如果查询返回0条结果,说明结构仅为两级;若有返回结果,则存在三级及以上层级。
方法2:直接返回验证结论
通过子查询直接输出验证结果,无需手动判断行数:
select case when exists ( select 1 from table1 child where exists ( select 1 from table1 parent where child.Parent_ID = parent.Company_ID and parent.Parent_ID is not null ) ) then '存在三级及以上层级' else '仅存在两级层级' end as 层级验证结果;
内容的提问来源于stack exchange,提问作者Vol Ren
相关产品推荐
相关产品推荐

