gpt4 book ai didi

SQLite 到 Postgres 层次结构查询

转载 作者:行者123 更新时间:2023-11-29 13:26:13 28 4
gpt4 key购买 nike

这是我在 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;

关于SQLite 到 Postgres 层次结构查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33455801/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com