Oracle 递归查询

递归查询

递归查询的语法

  1. SELECT [LEVEL], column, expr...
  2. FROM table
  3. [WHERE condition(s)]
  4. [START WITH condition(s)]
  5. [CONNECT BY PRIOR condition(s)] ;

使用语句SQL语句即可把整个递归树全部查询出来。

查询从King开始,从上往下的各级员工

  1. SELECT last_name||' reports to '||
  2. PRIOR last_name "Walk Top Down"
  3. FROM employees
  4. START WITH last_name = 'King'
  5. CONNECT BY PRIOR employee_id = manager_id ;

查询从101开始,从下往上的各级员工

  1. SELECT employee_id, last_name, job_id, manager_id
  2. FROM employees
  3. START WITH employee_id = 101
  4. CONNECT BY PRIOR manager_id = employee_id ;

使用LEVEL关键字和LPAD函数,在OUTPUT中显示树形层次

  1. SELECT LPAD(last_name, LENGTH(last_name)+(LEVEL*2)-2,'_')
  2. AS org_chart
  3. FROM employees
  4. START WITH last_name='King'
  5. CONNECT BY PRIOR employee_id=manager_id