+-
Oracle中显示树结构查询语句【子查父和父查子】

实际开发中可能会用到树状查询结果,语句如下:

select ID, LPAD(DEPT_NAME, LENGTH(DEPT_NAME) + (LEVEL * 2), ' ') dept_name
  from DEPT_INFO
 where IS_DEL = 0
 start with ID = 1
connect by prior ID = PAR_ID

--程序解释:
LPAD(DEPT_NAME, LENGTH(DEPT_NAME) + (LEVEL * 2), ' ') dept_name
LPAD:Oracle中查询关键字,
' ':为前面补齐的字符
Dept_name:为此结果列起的别名
start with ID = 1:树形开始 

-- 你还可以优化树的样式:

SELECT ID,
       LPAD('|-', (level - 1) * 4, ' | ') || LPAD('『', 2) || dept_name ||
       RPAD('』', 2) dept_name
  from DEPT_INFO
 where IS_DEL = 0
CONNECT BY PRIOR ID = PAR_ID
 start with ID = 1


--从子查父
select *
  from SYS_MODULE a
 start with mod_id = 111
connect by prior PAR_ID = MOD_ID


--从父查所有子
select *
  from SYS_MODULE a
 start with par_id = 100
connect by prior MOD_ID = PAR_ID