gpt4 book ai didi

sql - PostgreSQL with-delete "relation does not exists"

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

我正在使用 postgreSQL 9.1,我想使用这个提示从我的表中删除重复项: https://stackoverflow.com/a/3822833/2239537

所以,我的查询看起来像这样:

WITH cte
AS (SELECT ROW_NUMBER()
OVER (PARTITION BY code, card_id, parent_id
ORDER BY id DESC) RN
FROM card)
DELETE FROM cte
WHERE RN > 1

但它告诉我

ERROR: relation "cte" does not exist
SQL state: 42P01
Character: 157

但是这个语句工作正常:

WITH cte
AS (SELECT ROW_NUMBER()
OVER (PARTITION BY code, card_id, parent_id
ORDER BY id DESC) RN
FROM merchantcard)
SELECT * FROM cte
WHERE RN > 1

有什么想法可以让它发挥作用吗?谢谢!

最佳答案

那是因为 PostgreSQL 中的 CTE 与 SQL Server 中的 CTE 工作方式不同。在 SQL Server 中,CTE 就像一个可更新的 View ,因此您可以从中删除或更新它们,在 PostgreSQL 中则不能。

你可以加入cte和删除,比如:

with cte as (
select
id,
row_number() over(partition by code, card_id, parent_id order by id desc) as rn
from card
)
delete
from card
where id in (select id from cte where rn > 1)

另一方面,您可以在 PostgreSQL 的 CTE 中编写 DDL 语句(参见 documentation),这可能非常方便。例如,您可以删除 card 中的所有行,然后仅插入 row_number = 1 的行:

with cte1 as (
delete
from card
returning *
), cte2 as (
select
row_number() over(partition by code, card_id, parent_id order by id desc) as rn,
*
from cte1
)
insert into card
select <columns here>
from cte2
where rn = 1

关于sql - PostgreSQL with-delete "relation does not exists",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18439054/

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