在Oracle数据库

时间:2015-05-06 12:21:06

标签: oracle hierarchy hierarchical-data

使用CONNECT BY PRIOR在Oracle中存在分层查询。大家都知道,如何按父母选择孩子,但我需要按孩子选择父母。

这是我的表:

ID  PID     NAME            TYPE
1   null    EARTH           PLANET
2   1       USA             COUNTRY
3   2       CALIFORNIA      STATE
4   3       Los_Angeles     CITY
5   3       San_Francisco   CITY
6   3       San_Diego       CITY

在我的应用程序中,我有San_Diego的ID,我需要知道,San_Diego在哪个国家/地区?我需要用我的查询获得USA(TYPE = COUNTRY)吗?如何用oracle层次结构选择它?

4 个答案:

答案 0 :(得分:4)

层次结构意味着表格的一行是"父级",另一个是 - "孩子"。 PRIOR用于显示谁是谁。条款CONNECT BY PRIOR EMPNO = MGR表示如果两行具有相同的值,但是列EMPNO中的一行,而第二行 - 在列MGR中,则第二行是" parent"首先是一个孩子"。所以,查询

SELECT EMPNO,ENAME,MGR,LEVEL
FROM TMP_PCH
CONNECT BY PRIOR EMPNO = MGR
START WITH MGR = 'John'

返回John(和John本身)的所有下属,并查询

SELECT EMPNO,ENAME,MGR,LEVEL
FROM TMP_PCH
CONNECT BY PRIOR MGR = EMPNO
START WITH MGR = 'John'

返回John(和John本人)的所有老板。

答案 1 :(得分:1)

您需要为connect by创建正确的条件,然后从叶子'圣地亚哥'开始:

select name 
  from (
    select * from test 
      connect by id = prior pid
      start with name='San_Diego')
  where type='COUNTRY'

SQL Fiddle demo

答案 2 :(得分:1)

SELECT * FROM places_table
WHERE type = 'COUNTRY'
START WITH id = 6 -- San Diego
CONNECT BY PRIOR pid = id;

答案 3 :(得分:-1)

没有区别,你只需要在父方面使用PRIOR。例如,获取圣地亚哥市的树:

WITH your_table AS (  
  SELECT 1 id, NULL pid, 'EARTH' name, 'PLANET' type FROM dual
  UNION
  SELECT 2 id, 1 pid, 'USA' name, 'COUNTRY' type FROM dual
  UNION
  SELECT 3 id, 2 pid, 'CALIFORNIA' name, 'STATE' type FROM dual
  UNION 
  SELECT 4 id, 3 pid, 'Los_Angeles' name, 'CITY' type FROM dual
  UNION 
  SELECT 5 id, 3 pid, 'San_Francisco' name, 'CITY' type FROM dual
  UNION
  SELECT 6 id, 3 pid, 'San_Diego' name, 'CITY' type FROM dual
)
SELECT id, name, level
FROM your_table
CONNECT BY id = PRIOR pid
START WITH id = 6

如果您只想获得该国家/地区,则可以按级别进行过滤:

WITH your_table AS (  
  SELECT 1 id, NULL pid, 'EARTH' name, 'PLANET' type FROM dual
  UNION
  SELECT 2 id, 1 pid, 'USA' name, 'COUNTRY' type FROM dual
  UNION
  SELECT 3 id, 2 pid, 'CALIFORNIA' name, 'STATE' type FROM dual
  UNION 
  SELECT 4 id, 3 pid, 'Los_Angeles' name, 'CITY' type FROM dual
  UNION 
  SELECT 5 id, 3 pid, 'San_Francisco' name, 'CITY' type FROM dual
  UNION
  SELECT 6 id, 3 pid, 'San_Diego' name, 'CITY' type FROM dual
)
SELECT id, name, level
FROM your_table
WHERE LEVEL = 3
CONNECT BY id = PRIOR pid
START WITH id = 6