gpt4 book ai didi

sql - 查询一行中一个元素的父项和子项

转载 作者:行者123 更新时间:2023-12-04 06:58:52 25 4
gpt4 key购买 nike

我正在寻找在一行中显示父项和子项的最佳方式。
例子:

Table A
ID | PARENT_ID | VALUE
=============================
1 | | A
2 | 1 | B
3 | 2 | C
4 | | D
5 | 4 | E

所以我想得到以下结果:
 ID   |  PARENT      | CHILD     |  VALUE
=========================================
2 | 1 | 3 | A
5 | 4 | | E

你会如何解决这个问题?

任何帮助他非常感谢。

丹尼尔

最佳答案

您可以通过自联接轻松完成:

SQL> WITH table_a AS (
2 SELECT 1 ID, NULL parent_id, 'A' VALUE FROM dual
3 UNION ALL SELECT 2, 1, 'B' FROM dual
4 UNION ALL SELECT 3, 2, 'C' FROM dual
5 UNION ALL SELECT 4, NULL, 'D' FROM dual
6 UNION ALL SELECT 5, 4, 'E' FROM dual
7 )
8 SELECT children.id, children.parent_id,
9 grand_children.id, children.value
10 FROM (SELECT ID, parent_id, VALUE
11 FROM table_a
12 WHERE LEVEL = 2
13 CONNECT BY parent_id = PRIOR ID
14 START WITH parent_id IS NULL) children
15 LEFT JOIN table_a grand_children
16 ON children.id = grand_children.parent_id;

ID PARENT_ID ID VALUE
---------- ---------- ---------- -----
2 1 3 B
5 4 E

关于sql - 查询一行中一个元素的父项和子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2190347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com