我正在将 Oracle 数据库迁移到 PosgreSQL。我有这样一个分层查询,如下所示。我成功地做了更简单的分层查询。但我不能做这个查询。有人可以帮忙查询 PostgreSQL 吗?
Oracle查询:
select count(*) cnt
from list nl,
parts spl
where nl.month = Month_
and nl.year = Year_
and nl.date_del is null
and nl.id(+) = spl.id
and nl.dep_owner = dep_owner_
and nl.dep_id in ( select d.dep_id
from departments d
connect bt prior d.dep_id = d.parent_id
start with d.dep_id = dep_id_)
connect by prior spl.id = spl.parent_id
start with spl.index = trim(part_index_)
Postgres查询:
WITH RECURSIVE cteroot AS (SELECT count(*) AS cnt
FROM parts spl
LEFT JOIN list nl ON spl."ID" = nl."ID"
where nl."MONTH"= Month_
and nl."YEAR" = Year_
and nl."DATE_DEL" is null
and nl."DEP_OWNER" = dep_owner_
and nl."DEP_ID" IN (WITH RECURSIVE cte AS (SELECT "DEP_ID"
FROM departments
where "DEP_ID"= dep_id_
UNION
SELECT d."DEP_ID"
FROM departments d
JOIN cte ON d."PARENT_ID"= cte."DEP_ID")
SELECT "DEP_ID"
FROM cte
)
and spl."INDEX" = TRIM(part_index_)
UNION
SELECT count(*) AS cntd
FROM parts spld
LEFT JOIN list nld ON spl."ID" = nld."ID"
where nld."MONTH"= Month_
and nld."YEAR" = Year_
and nld."DATE_DEL" is null
and nld."DEP_OWNER" = dep_owner_
and nld."DEP_ID" IN (WITH RECURSIVE cted AS (SELECT "DEP_ID"
FROM departments dt
where dt."DEP_ID"= dep_id_
UNION
SELECT td."DEP_ID"
FROM departments td
JOIN cted ON td."PARENT_ID"= cted."DEP_ID")
SELECT "DEP_ID"
FROM cted
)
SELECT count(*) cntv
FROM cteroot)`
此代码有效但不正确
您没有在 Oracle 查询中使用
LEFT OUTER JOIN
。是的,您可以在联接中使用 (+)
,但在 START WITH
和 CONNECT BY
子句中,您需要 spl.index
和 spl.id
等于另一个值,并且当 OUTER JOIN
发生并且vlues 将是 NULL
所以连接只能是 INNER JOIN
.
因此,您的 Oracle 查询实际上是:
SELECT COUNT(*) cnt
FROM list l
INNER JOIN parts p
ON ( l.id = p.id )
WHERE l.month = Month_
AND l.year = Year_
AND l.date_del IS NULL
AND l.dep_owner = dep_owner_
AND l.dep_id IN ( SELECT d.dep_id
FROM departments d
CONNECT BY PRIOR d.dep_id = d.parent_id
START WITH d.dep_id = dep_id_ )
CONNECT BY PRIOR p.id = p.parent_id
START WITH p.index = trim(part_index_)
至少,您需要将
LEFT JOIN
s更改为INNER JOIN
s。