Hierarchical relational SQL query

As we all know, there must be a field of parent Id in the general table of hierarchical query, which is generally represented by parent_id. For the convenience of retrieval, most companies will set up a path field to record the status of the current level to prove the current level. The position in the current hierarchy chain.
When we have the information of the current path, it is relatively simple to obtain all its subordinates. We only need to fuzzy match the right side, but it will be more complicated when we want to obtain all the current superior chains, because our current The upper level of the hierarchy may have multiple subordinates, and we are only one of the current branches, so it will be more troublesome when we want to obtain a chain, and it is impossible for us to repeatedly call the database to obtain according to the parent_id, which is a waste of resources. Next I show how to get it.

Take a chestnut:

Hierarchical relationship display

# 获取当前组织所有子组织path,#{path}是咱们自己传入的参数,为了不影响整体性,用引号包了起来
SELECT path FROM organization WHERE path LIKE CONCAT('000001', '%') and deleted = 0;

# 获取当前组织所有上级组织链中的组织path,#{path}是咱们自己传入的参数,为了不影响整体性,用引号包了起来
SELECT path FROM organization WHERE '000001' LIKE CONCAT(path, '%') and deleted = 0;

Let me show you the returned results of the above two SQL executions:

  • After the first SQL is executed, the results are displayed
    show subordinates
  • After the second SQL execution is completed, the results will be displayed.
    show superior
    Note:
    It should be noted that whether the query is superior or subordinate, it includes itself and needs to be processed by itself.

Guess you like

Origin blog.csdn.net/weixin_43650254/article/details/123790038