SQLite到Postgres层次结构查询



这里有一个我在SQLite中成功使用的查询。它创建了属于"Pak"的所有链接的层次结构。

WITH LinkTree(link_id, link_pid, pak_id, link_name, depth)
AS
(
SELECT *, 0 AS depth FROM links
WHERE link_pid = 0
UNION ALL
SELECT l.*, lt.depth+1 AS depth FROM LinkTree lt
JOIN links l ON (lt.link_id = l.link_pid)
)
SELECT * FROM LinkTree WHERE pak_id = 1; 

我正试图修改它,使其与Postgres一起使用,但我收到了一个错误,说"深度"令人震惊。

使用了两个简单的表格:

Paks: pak_id, pak_name
Links: link_id, link_pid, link_name, pak_id

除了*_name是varchars之外,所有列都是整数。

有人能帮我吗?

我认为您需要RECURSIVE关键字:

WITH RECURSIVE LinkTree(link_id, link_pid, pak_id, link_name, depth)
AS
(
SELECT *, 0 AS depth FROM links
WHERE link_pid = 0
UNION ALL
SELECT l.*, lt.depth+1 AS depth FROM LinkTree lt
JOIN links l ON (lt.link_id = l.link_pid)
)
SELECT * FROM LinkTree WHERE pak_id = 1; 

编辑:

不要在选择:中使用*

WITH LinkTree(link_id, link_pid, pak_id, link_name, depth)
AS
(
  SELECT link_id, link_pid, pak_id, link_name, 0 AS depth 
  FROM links
  WHERE link_pid = 0
  UNION ALL
  SELECT l.link_id, l.link_pid, l.pak_id, l.link_name, lt.depth+1 AS depth 
  FROM LinkTree lt
  JOIN links l 
    ON lt.link_id = l.link_pid
)
SELECT * 
FROM LinkTree 
WHERE pak_id = 1; 

相关内容

  • 没有找到相关文章

最新更新