有下圖這樣一張表,它記錄的是員工的一些信息,m_id該員工的上級的id,例如James就是Ron的上級;
那麼咱們如何找出他們的層級關係。sql
oracle爲咱們提供的Select語句的Connect by和start with子句能夠執行層次查詢;
語法以下:express
select [level], column, expression, ... form table [where where_caluase] [start with start_condtion connect by prior prior_condition] --level 是一個僞列,表明了第幾層,對於本表的CEO,天然是第一層 --start_condtion 定了層次化查詢的起點,當編寫層次化查詢時必須指定start with子句; --prior_condition 定義了父行和子行之間的關係,當編寫層次化查詢時必須定義connect by prior子句
實例:oracle
--employee_id 就是表中的id --manager_id 就是表中的m_id select level, employee_id, manager_id, first_name, last_name from more_employees start with employee_id =1 connect by prior employee_id = manager_id order by level;
select first_name || ' ' || last_name as employee from more_employees start with first_name = 'Susan' connect by prior employee_id = manager_id;