我有一个客户的非二叉树,我需要为给定节点获取树中的所有 ID。
该表非常简单,只是一个带有父ID和子ID的连接表。这是我存储在数据库中的树的表示。
在这个例子中,如果我搜索节点 17,我需要返回 14-17。如果我搜索 11,我需要返回 1-6-5-4-8-11-12-7-2-10-3。
顺序并不重要。在将子节点添加到节点时,我只需要 ID 以避免循环。
我创建了这个查询。祖先部分工作正常,我检索了所有父节点,但对于后代我有一些麻烦。我只能检索树的某些部分。例如,对于节点 11,我检索 4-10-6-11-7-8,因此树的所有正确部分都丢失了。
WITH RECURSIVE
-- starting node(s)
starting (parent, child) AS
(
SELECT t.parent, t.child
FROM public.customerincustomer AS t
WHERE t.child = :node or t.parent = :node
)
,
ancestors (parent, child) AS
(
SELECT t.parent, t.child
FROM public.customerincustomer AS t
WHERE t.parent IN (SELECT parent FROM starting)
UNION ALL
SELECT t.parent, t.child
FROM public.customerincustomer AS t JOIN ancestors AS a ON t.child = a.parent
),
descendants (parent, …
Run Code Online (Sandbox Code Playgroud) 我需要在我的表中添加一列,其中包含每次出现的次数。因此,如果值是唯一的,则列值应为 1,但如果有多个副本,我需要为每一行 (1,2...) 设置一个不同的值
例如,数据库是 postgres
ID | 价值 | 数数 |
---|---|---|
1 | 一种 | 1 |
2 | 一种 | 2 |
3 | 乙 | 1 |
4 | 乙 | 2 |
5 | 乙 | 3 |
6 | C | 1 |
数据库示例https://dbfiddle.uk/?rdbms=postgres_10&fiddle=0e7132f3f094bd93b390ccae2e811696