postgresql - 删除递归 child

标签 postgresql sql-delete recursive-query

我有以下 sql 可以获取根论坛帖子的所有子孙。

with recursive all_posts (id, parentid, root_id) as
                (
                select t1.id,
                t1.parent_forum_post_id as parentid,
                t1.id as root_id
                from forumposts t1

                union all

                select c1.id,
                c1.parent_forum_post_id as parentid,
                p.root_id
                from forumposts
                c1
                join all_posts p on p.id = c1.parent_forum_post_id
                )

                select fp.id
                from forumposts fp inner join all_posts ap
                on fp.id=ap.id 
                where
                root_id=1349 
                group by fp.id

问题是我希望删除选定的记录。类似于 delete from forumposts fp where fp.id=(last select from the code above) 但这不起作用(我在“DELETE”处或附近收到语法错误)。这是我第一次使用递归,我一定遗漏了一些东西。感谢您的帮助。

最佳答案

您可以简单地使用 DELETE 语句而不是 SELECT 来完成您的工作:

with recursive all_posts (id, parentid, root_id) as (
    select t1.id,
    t1.parent_forum_post_id as parentid,
    t1.id as root_id
    from forumposts t1

    union all

    select c1.id,
    c1.parent_forum_post_id as parentid,
    p.root_id
    from forumposts
    c1
    join all_posts p on p.id = c1.parent_forum_post_id
)
DELETE FROM forumposts
 WHERE id IN (SELECT id FROM all_posts WHERE root_id=1349);

其他可能的组合,例如根据子表中已删除的行从主表中删除,check out the documentation .

编辑:对于 9.1 之前的 PostgresSQL 版本,您可以像这样使用初始查询:

DELETE FROM forumposts WHERE id IN (
    with recursive all_posts (id, parentid, root_id) as (
        select t1.id,
        t1.parent_forum_post_id as parentid,
        t1.id as root_id
        from forumposts t1

        union all

        select c1.id,
        c1.parent_forum_post_id as parentid,
        p.root_id
        from forumposts c1
        join all_posts p on p.id = c1.parent_forum_post_id
    )
    select id from all_posts ap where root_id=1349
);

关于postgresql - 删除递归 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10381243/

相关文章:

sql - 删除在另一个表中没有匹配项的记录

MYSQL删除同组重复记录只保留一条

sql - 使用 select * 的递归查询引发 ORA-01789

Postgresql 空间查询太慢

postgresql - psycopg2 不插入 unicode 数据

json - 对未知键的 Postgres JSON 查询

django - 操作错误 : FATAL: database "django" does not exist

mysql删除连续的行

postgresql - 递归 CTE PostgreSQL 将多个 ID 与其他字段的附加逻辑连接起来

PHP 产品类别选择下拉列表,允许用户将类别定义为主类别或子类别