postgresQL 的递归查询 parent/child
Recursive query for postgresSQL parent/child
寻求有关递归查询语法的一些帮助,当然还有结果。
如您所见,我有一个 table,类别为 parent 和 child(parent 可以有无限 children)。查询分类字典(链接到真实分类)
我只想 return 每个类别树的最后一个 child
更新了我的代码和信息
编辑
WITH RECURSIVE cat(id) AS (
SELECT
*
FROM
category_dictionary
LEFT JOIN category_dictionary.category ON category.id
WHERE
category.parent is NOT NULL
UNION
SELECT
*
FROM
cat
LEFT JOIN cat.category ON category.id
WHERE
category.parent is NOT NULL
)
SELECT
*
FROM
cat
Table信息:
Category_dictionary
是一个table参数类别 上的连接类别
Category
是主要的 table 和 Parent 条目。
示例数据:
category_dictionary
条目:
ID : name (Men) : category_id
category
个条目:
category_id : name : parent (null or category_id)
因此我想要每个类别条目的所有最后 child,我的意思是没有 child 的类别。
不需要递归查询来找到最深的 children。相反,人们会查看不是 parent 的条目(因此不存在其他 child)。此类条目 ID 未包含在 parent
列中。
然后您可以将此类别加入其他表格
SELECT *
FROM category cat
JOIN category_dictionary cat_dic ON cat.id = cat_dic.id
WHERE NOT EXISTS
(SELECT 1 FROM category cat2
WHERE cat2.parent = cat.id);
寻求有关递归查询语法的一些帮助,当然还有结果。
如您所见,我有一个 table,类别为 parent 和 child(parent 可以有无限 children)。查询分类字典(链接到真实分类)
我只想 return 每个类别树的最后一个 child
更新了我的代码和信息
编辑
WITH RECURSIVE cat(id) AS (
SELECT
*
FROM
category_dictionary
LEFT JOIN category_dictionary.category ON category.id
WHERE
category.parent is NOT NULL
UNION
SELECT
*
FROM
cat
LEFT JOIN cat.category ON category.id
WHERE
category.parent is NOT NULL
)
SELECT
*
FROM
cat
Table信息:
Category_dictionary
是一个table参数类别 上的连接类别
Category
是主要的 table 和 Parent 条目。
示例数据:
category_dictionary
条目:
ID : name (Men) : category_id
category
个条目:
category_id : name : parent (null or category_id)
因此我想要每个类别条目的所有最后 child,我的意思是没有 child 的类别。
不需要递归查询来找到最深的 children。相反,人们会查看不是 parent 的条目(因此不存在其他 child)。此类条目 ID 未包含在 parent
列中。
然后您可以将此类别加入其他表格
SELECT *
FROM category cat
JOIN category_dictionary cat_dic ON cat.id = cat_dic.id
WHERE NOT EXISTS
(SELECT 1 FROM category cat2
WHERE cat2.parent = cat.id);