Hierarchical Query in MySQL. (connect by equivalent for MySQL)

前端 未结 1 373
有刺的猬
有刺的猬 2021-01-26 09:38

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

Table Name : tb_corp
----------------------------------------         


        
1条回答
  •  借酒劲吻你
    2021-01-26 10:23

    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)
提交回复
热议问题