想把查询从Oracle迁移到PostgreSQL [关闭]

pbpqsu0x  于 2023-03-22  发布在  Oracle
关注(0)|答案(1)|浏览(159)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

昨天关门了。
Improve this question
质询:

Select n 
  from tab1
 where id in (select id 
                from tab2
               start with id=5
             connect by prior parentid=tab2.id) 
   and n like ‘N_%’

我尝试了下面的查询,但它没有给我正确的输出。所以我需要帮助在这里

With recursive a as (
Select n from tab1 where n like ‘N_%’
Union all
Select id from tab2 join tab2.id=tab1.id)
Select * from a;

查询正在工作,但输出延迟与oracle

avwztpqn

avwztpqn1#

你需要先递归,然后过滤结果(而不是试图同时连接和过滤):

WITH RECURSIVE a AS (
  SELECT id, parentid
  FROM   tab2
  WHERE  id = 5 -- START WITH clause
UNION ALL
  SELECT tab2.id, tab2.parentid
  FROM   tab2
         INNER JOIN a
         ON a.parentid = tab2.id -- CONNECT BY clause
)
SELECT n
FROM   tab1
WHERE  id IN (SELECT id FROM a)
AND    n LIKE 'N_%';

其中,对于示例数据:

CREATE TABLE tab1 (n VARCHAR(20), id INT);
CREATE TABLE tab2 (id INT, parentid INT);

INSERT INTO tab1 (n, id)
  SELECT 'NX01', 1 UNION ALL
  SELECT 'XX02', 2 UNION ALL
  SELECT 'NY03', 3 UNION ALL
  SELECT 'NX04', 4;

INSERT INTO tab2 (id, parentid)
  SELECT 5, 1 UNION ALL
  SELECT 1, 2 UNION ALL
  SELECT 2, 4 UNION ALL
  SELECT 4, NULL;

输出:
| 数量|
| - ------|
| NX01|
| 公司简介|
PostgreSQL fiddleOracle fiddle

相关问题