如何使用oracle编写循环查询

vlurs2pr  于 2023-08-04  发布在  Oracle
关注(0)|答案(1)|浏览(107)

我有这张table
| i1| i2| i2 |
| --|--| ------------ |
| x1| a1| a1 |
| x1| A2| a2 |
| a1| A5| a5 |
| A2| A3| a3 |
| A3| A4| a4 |
i1和i2之间的关系是i2包含i1,所以a1包含x1,a5包含a1,我想得到所有项目的最终关系。
预期的结果是
| i| i_final| i_final |
| --|--| ------------ |
| x1| A5| a5 |
| x1| A4| a4 |
| a1| A5| a5 |
| A2| A4| a4 |
| A3| A4| a4 |

z31licg0

z31licg01#

你不想要一个“循环”。您希望使用分层查询并查找每个根的分层树的叶子:

SELECT id,
       CONNECT_BY_ROOT i1 AS i1,
       i2
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY
       PRIOR i2 = i1
AND    PRIOR id = id -- Not sure if this is needed as you only have one id value

字符串
其中,对于样本数据:

CREATE TABLE table_name (id, i1, i2) AS
SELECT 'Y001', 'x1', 'a1' FROM DUAL UNION ALL
SELECT 'Y001', 'x1', 'a2' FROM DUAL UNION ALL
SELECT 'Y001', 'a1', 'a5' FROM DUAL UNION ALL
SELECT 'Y001', 'a2', 'a3' FROM DUAL UNION ALL
SELECT 'Y001', 'a3', 'a4' FROM DUAL;


输出:
| I1| I2| I2 |
| --|--| ------------ |
| a1| A5| a5 |
| A2| A4| a4 |
| A3| A4| a4 |
| x1| A5| a5 |
| x1| A4| a4 |
fiddle

相关问题