SQLite到Postgres层次结构查询

时间:2015-10-31 19:38:41

标签: sql postgresql recursive-query

这是我成功与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

所有列都是整数,除了作为varchars的* _name'

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

我认为您需要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;