sql - 如何从 Oracle 中的链表中获取第一个元素?

标签 sql oracle oracle11g

我的 Oracle-DB 中有一个表,如下所示:

╔════╦════════════════╦═════════════╗
║ ID ║ Predecessor_id ║ Information ║
╠════╬════════════════╬═════════════╣
║ 1  ║     NULL       ║    foo      ║
║ 2  ║     1          ║    bar      ║
║ 3  ║     2          ║    muh      ║
║ 4  ║     NULL       ║    what     ║
║ 5  ║     4          ║    ever     ║
╚════╩════════════════╩═════════════╝

我需要一个 SELECT 返回如下内容:
╔════╦════════════════╦════════════════════╦═════════════╗
║ ID ║ Predecessor_id ║ First_list_element ║ Information ║
╠════╬════════════════╬════════════════════╬═════════════╣
║ 1  ║     NULL       ║         1          ║    foo      ║
║ 2  ║     1          ║         1          ║    bar      ║
║ 3  ║     2          ║         1          ║    muh      ║
║ 4  ║     NULL       ║         4          ║    what     ║
║ 5  ║     4          ║         4          ║    ever     ║
╚════╩════════════════╩════════════════════╩═════════════╝

该表具有某种链接列表方面。 List 的第一个元素是没有前任的元素。我需要的是 List 所属的每一行的信息。该列表由第一个元素的 ID 定义。

在编程语言中,我会实现某种查找表。但在 SQL 中我不知道。我更喜欢 SQL,但如果只有 PL/SQL 给我一个响应,我也会接受。

最佳答案

您应该使用 CONNECT_BY_ROOT 运算符

When you qualify a column with this operator, Oracle returns the column value using data from the root row. This operator extends the functionality of the CONNECT BY [PRIOR] condition of hierarchical queries. http://docs.oracle.com/cd/B19306_01/server.102/b14200/operators004.htm#i1035022



http://sqlfiddle.com/#!4/121f02/1
create table  tbl(
id number,
Predecessor_id number,
Information varchar2(250));


insert into tbl values(1 ,NULL          ,'foo'    );
insert into tbl values(2 ,1             ,'bar'    );
insert into tbl values(3 ,2             ,'muh'    );
insert into tbl values(4 ,NULL          ,'what'   );
insert into tbl values(5 ,4             ,'ever'   );

SELECT tbl.*, connect_by_root id first_list_element
  FROM tbl
CONNECT BY PRIOR id = predecessor_id
 START WITH predecessor_id IS NULL

关于sql - 如何从 Oracle 中的链表中获取第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33253826/

相关文章:

sql - 连接两个具有不同数据的相同表结构

sql - MSSQL : How do you script Stored Procedure creation with code?

sql - Oracle SQL 比较包含数字的字符串,从 0(零)开始

SQL CHECKSUM_AGG(BINARY_CHECKSUM(*)) 对具有相似内容的 2 个不同表给出相同的结果

c# - 在更新查询中出现语法错误

sql - 用PLSQL中的另一个数字替换日期中的日期部分

sql - 如何直接从 PL/SQL 调用 PRO*C 程序?

sql - 减少查询的缓冲区缓存命中会导致随机性能问题

sql - 将数字转换为小数精度为 3 的数字的正则表达式

mysql - Oracle DB - 无序列主键自增列