我正在阅读PostgreSQL递归查询文档时遇到一些问题,不知道是否有人能够提供以下内容的建议。
这是数据:
Table "public.subjects"
Column | Type | Collation | Nullable | Default
-------------------+-----------------------------+-----------+----------+--------------------------------------
id | bigint | | not null | nextval('subjects_id_seq'::regclass)
name | character varying | | |
Table "public.subject_associations"
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+--------------------------------------------------
id | bigint | | not null | nextval('subject_associations_id_seq'::regclass)
parent_id | integer | | |
child_id | integer | | |
这里,“主题”可以有很多父级和很多子级。当然,在最高层级上,一个主题没有父级,在最低层级上没有子级。例如:
parent_id | child_id
------------+------------
2 | 3
1 | 4
1 | 3
4 | 8
4 | 5
5 | 6
6 | 7
我要找的是从一个子代ID开始获取所有祖先,以及从一个父代ID开始获取所有后代。 因此:
parent_id 1 -> children 3, 4, 5, 6, 7, 8
parent_id 2 -> children 3
child_id 3 -> parents 1, 2
child_id 4 -> parents 1
child_id 7 -> parents 6, 5, 4, 1
虽然似乎有很多类似的例子,但我很难理解它们,因此欢迎任何我可以尝试的建议。