在postgresql中用行号更新表

问题描述

尝试更新具有唯一 iD 列的表,因为其中没有唯一键列。

使用以下 CTE 时,我收到更新语句中 CTE 名称不存在关系的错误。但是在执行 select 语句时同样可以正常工作。

使用的查询

With updateid As
(
SELECT 
ID,ROW_NUMBER() OVER (ORDER BY Model DESC) AS RN
FROM aud
)UPDATE updateid SET ID='AUD'||repeat('0',5-length(cast(RN as varchar)))||cast(RN as varchar)

遇到错误

ERROR:  relation "updateid" does not exist
LINE 7: )UPDATE updateid SET ID='AUD'+replicate('0',5-len(cast(RN as...
                ^
sql state: 42P01
Character: 95

运行良好的 select 语句:

With updateid As
(
SELECT 
ID,ROW_NUMBER() OVER (ORDER BY Model DESC) AS RN
FROM aud
)Select * from updateid

解决方法

您可以为此使用一个序列:

df = pd.read_csv('../DATA/moviereviews.csv')

我不建议将主键设为字符串,因为您的代码表明您想要这样做。但是,如果需要,您当然可以将该逻辑放入 create sequence temp_sequence_x; update t set id = nextval('temp_sequence_x'); drop sequence temp_sequence_x; 子句中。

Here 是一个 dbfiddle。

注意:如果有一组唯一的键,则有替代方法。但是,您的问题没有提供该信息。而且,序列方法非常简单。

,

如果您仍然想从某个源结果集中更新表,您可以使用 update ... from ...where 子句中指定的连接条件:

create table t
as
select q,null::int as w
from unnest(array[1,2,3]) as q
with s as (
  select row_number() over(order by q desc) as rn,ctid as row_id
  from t
)
update t
set w = rn
from s
where t.ctid = s.row_id
select *
from t
 q |  w
-: | -:
 3 |  1
 2 |  2
 1 |  3

dbfiddle here