mysql 实现分层查询,MySQL中的分层查询。 (以等效方式连接MySQL)

I have three fields in a table that define a hierarchical relationship present in a MySQL database.

Table Name : tb_corp

--------------------------------------------

comp_code | incharge_comp_Code | mngr_emp_no

A | | 111

--------------------------------------------

B | A |

--------------------------------------------

C | B |

--------------------------------------------

How do I write a query to obtain all the comp_code that mngr_emp_no = 111 is in charge. According to the table above, 111 is in charge of three companies(A, B, and C). The reason is that A company is in charge of B company and B company is in charge of C company as a result A is also in charge of C company.

(A -> B) (B -> C) == (A -> C)

解决方案

There is no native hierarchical query support in MySQL.

For a finite number of levels to be traversed, we can write queries that get result for each level, and combine the results with a UNION ALL operator.

Or, we can write a MySQL stored program (procedure) for a more recursive approach.

As an example of approach using a native SQL query:

SELECT t0.comp_code

FROM tb_corp t0

WHERE t0.mgr_emp_no = 111

UNION ALL

SELECT t1.comp_code

FROM tb_corp t0

JOIN tb_corp t1 ON t1.incharge_comp_code = t0.comp_code

WHERE t0.mgr_emp_no = 111

UNION ALL

SELECT t2.comp_code

FROM tb_corp t0

JOIN tb_corp t1 ON t1.incharge_comp_code = t0.comp_code

JOIN tb_corp t2 ON t2.incharge_comp_code = t1.comp_code

WHERE t0.mgr_emp_no = 111

UNION ALL

SELECT t3.comp_code

FROM tb_corp t0

JOIN tb_corp t1 ON t1.incharge_comp_code = t0.comp_code

JOIN tb_corp t2 ON t2.incharge_comp_code = t1.comp_code

JOIN tb_corp t3 ON t3.incharge_comp_code = t2.comp_code

WHERE t0.mgr_emp_no = 111

etc. This approach can be extended to t4, t5, t6, ... down to some (reasonable) finite number of levels.

For a more recursive approach, a MySQL stored program (PROCEDURE) can be written.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值