递归查找
作为一个例子,看看这段代码:
CREATE VIEW
mvw_pre_import_cellpath_check
(
pkid_cell,
id_cell ,
id_parent,
has_child,
id_path ,
name_path,
string_path
) AS WITH RECURSIVE cell_paths
(
pkid_cell,
id_cell ,
id_parent,
id_path ,
name_path
) AS
(
SELECT
tbl_cell.pkid ,
tbl_cell.cell_id ,
tbl_cell.cell_parent_id ,
ARRAY[tbl_cell.cell_id] AS "array",
ARRAY[tbl_cell.cell_name] AS "array"
FROM
ufo.tbl_cell
WHERE
(((
tbl_cell.cell_parent_id IS NULL)
AND (
tbl_cell.reject_reason IS NULL))
AND (
tbl_cell.processed_dt IS NULL))
UNION ALL
SELECT
tbl_cell.pkid ,
tbl_cell.cell_id ,
tbl_cell.cell_parent_id ,
(cell_paths_1.id_path || tbl_cell.cell_id),
(cell_paths_1.name_path || tbl_cell.cell_name)
FROM
(cell_paths cell_paths_1
JOIN
ufo.tbl_cell
ON
((
tbl_cell.cell_parent_id = cell_paths_1.id_cell)))
WHERE
(((
NOT (
tbl_cell.cell_id = ANY (cell_paths_1.id_path)))
AND (
tbl_cell.reject_reason IS NULL))
AND (
tbl_cell.processed_dt IS NULL))
)
SELECT
cell_paths.pkid_cell,
cell_paths.id_cell ,
cell_paths.id_parent,
(
SELECT
COUNT(*) AS COUNT
FROM
ufo.tbl_cell x
WHERE
((
cell_paths.id_cell = x.cell_id)
AND (
EXISTS
(
SELECT
1
FROM
ufo.tbl_cell y
WHERE
(
x.cell_id = y.cell_parent_id))))) AS has_child,
cell_paths.id_path ,
cell_paths.name_path ,
array_to_string(cell_paths.name_path, ' -> '::text) AS string_path
FROM
cell_paths
ORDER BY
cell_paths.id_path;
在寻找递归 CTE 时,还有更多关于 SO 的示例。但与您的示例相反,在我的示例中,顶级单元(经理)具有 parent_id = NULL。这些是不同分支的起点。
高温高压