删除主键列后如何重新创建主键?

时间:2013-09-17 23:52:52

标签: sql postgresql

我想在第8.4页重新创建一个主键列。但我正在尝试的查询不起作用(它实际上没有执行):

update beta
set id=rown
from 
    (select row_number() as rown 
    from beta as b over (order by b.id) -- b.id is null on all rows
    ) q;

2 个答案:

答案 0 :(得分:2)

你试过这个解决方案吗?始终先备份所有东西。

--Approach 2: Closer to Hubert's Examples
--Advantage: Easy to read - intuitive, doesn't rely on a primary key
--Disadvantage: Creates temp junk in the db 
--      which means reusing in same session you must drop
--  and using in nested subquery results may be unpredictable

CREATE TEMP sequence temp_seq;
SELECT nextval('temp_seq') As row_number, oldtable.*
FROM (SELECT * FROM beta) As oldtable;

http://www.postgresonline.com/journal/archives/79-Simulating-Row-Number-in-PostgreSQL-Pre-8.4.html

答案 1 :(得分:0)

您应该使用ALTER TABLE命令

ALTER TABLE beta ADD PRIMARY KEY (id);

此链接应有助于http://www.postgresql.org/docs/current/static/sql-altertable.html