如何获取子记录或父记录SQL

时间:2019-01-18 21:34:24

标签: sql

如果我有一个表,该表具有一个称为ID的uniqueidentifier主键,并且有一个名为parentId的列,该列指向该表可能链接到的同一表中的另一条记录(对于父记录,列为null,则子记录具有(父记录的ID),如果存在一个子记录,又没有子记录,我将如何搜索并拉回一个子记录?我正在使用不是主键的另一列中的数据搜索该表。

1 个答案:

答案 0 :(得分:1)

我相信您正在寻找的是按级别连接。

https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:489772591421

我从上面的链接中获取了代码,并将其放在下面。我讨厌死链接,因此这将使答案在Stackoverflow上保持活跃。

我不喜欢提供利用DDL的示例,因为并非每个人都有创建表等的数据库特权。下面的示例仅适用于普通SQL(仅使用DML)。我喜欢使用With Blocks在这样的简单示例(又名Common Table Expression-CTE)中形成表格。

WITH sample_data AS
(
    SELECT 'KING'   AS ENAMe, 7839 AS EMPNO, NULL AS MGR FROM DUAL UNION ALL
    SELECT 'JONES'  AS ENAMe, 7566 AS EMPNO, 7839 AS MGR FROM DUAL UNION ALL
    SELECT 'SCOTT'  AS ENAMe, 7788 AS EMPNO, 7566 AS MGR FROM DUAL UNION ALL
    SELECT 'ADAMS'  AS ENAMe, 7876 AS EMPNO, 7788 AS MGR FROM DUAL UNION ALL
    SELECT 'FORD'   AS ENAMe, 7902 AS EMPNO, 7566 AS MGR FROM DUAL UNION ALL
    SELECT 'SMITH'  AS ENAMe, 7369 AS EMPNO, 7902 AS MGR FROM DUAL UNION ALL
    SELECT 'BLAKE'  AS ENAMe, 7698 AS EMPNO, 7839 AS MGR FROM DUAL UNION ALL
    SELECT 'ALLEN'  AS ENAMe, 7499 AS EMPNO, 7698 AS MGR FROM DUAL UNION ALL
    SELECT 'WARD'   AS ENAMe, 7521 AS EMPNO, 7698 AS MGR FROM DUAL UNION ALL
    SELECT 'MARTIN' AS ENAMe, 7654 AS EMPNO, 7698 AS MGR FROM DUAL UNION ALL
    SELECT 'TURNER' AS ENAMe, 7844 AS EMPNO, 7698 AS MGR FROM DUAL UNION ALL
    SELECT 'JAMES'  AS ENAMe, 7900 AS EMPNO, 7698 AS MGR FROM DUAL UNION ALL
    SELECT 'CLARK'  AS ENAMe, 7782 AS EMPNO, 7839 AS MGR FROM DUAL UNION ALL
    SELECT 'MILLER' AS ENAMe, 7934 AS EMPNO, 7782 AS MGR FROM DUAL
)

SELECT lpad(' ',LEVEL*2,' ')||ename ename, empno, mgr
FROM sample_data
START WITH MGR IS NULL
CONNECT BY PRIOR EMPNO = MGR
;

下面的屏幕截图显示了它的作用。

enter image description here