在 postgresql 中用行号更新 table

Updating a table with row number in postgresql

尝试使用唯一的 iD 列更新 table,因为其中没有唯一的键列。

使用以下 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

您可以为此使用序列:

create sequence temp_sequence_x;

update t
    set id = nextval('temp_sequence_x');

drop sequence temp_sequence_x;

我不建议将主键设为字符串,因为您的代码建议您这样做。但是,如果需要,您当然可以将该逻辑放入 set 子句中。

Here 是一个 db<>fiddle.

注意:如果有一组键是唯一的,那么还有其他方法。但是,您的问题没有提供该信息。而且,顺序方法非常简单。

如果您仍想从某些源结果集中更新 table,您可以使用 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

db<>fiddle here