zet*_*tah 15 postgresql migration postgresql-9.3
我在 Postgresql 中有一个数据库,它是从 SQL Server 迁移过来的(只有数据)。
在 SQL Server 上,此数据库中的表具有以下列:
measure_id
datum
measure
Run Code Online (Sandbox Code Playgroud)
其中measure_id
是自动增量主键,datum
是日期时间,measure
是浮点数。
在 Postrgresql 中迁移后,measure_id
是 bigint 类型的列。
measure_id
既然我的表充满了数据,我该如何将此列 ( )更改为 bigserial 并将其指定为主键?
a_h*_*ame 21
创建一个序列并将其用作列的默认值:
create sequence measures_measure_id_seq
owned by measures.measure_id;
alter table measures
alter column measure_id set default nextval('measures_measure_id_seq');
commit;
Run Code Online (Sandbox Code Playgroud)
这基本上是什么serial
。
有关详细信息,请参阅手册:http :
//www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL
小智 5
我看到该问题已标记为已解决,但是,正如评论中指出的那样,它缺少现有记录已在相关列中设置了某些值的情况。
我还将列出一些其他案例。
products
我正在为架构中存在的名为 的表执行此操作public
。正在对该表的列进行自动增量id
。
1. 对于不存在的列
-- auto-increment constraint for a new column
ALTER TABLE public.products
ADD COLUMN id SERIAL PRIMARY KEY;
Run Code Online (Sandbox Code Playgroud)
2. 对于表中没有值的现有列
-- create sequence
CREATE SEQUENCE public_products_id_seq OWNED BY public.products.id;
-- use sequence for the target column
ALTER TABLE public.products ALTER COLUMN id SET DEFAULT nextval('public_products_id_seq');
Run Code Online (Sandbox Code Playgroud)
3. 对于表中已经有一些值的现有列
-- create sequence
CREATE SEQUENCE public_products_id_seq OWNED BY public.products.id;
-- set the current value of the sequence to the max value from that column
-- (id column in this scenario)
SELECT SETVAL('public_products_id_seq', (select max(id) from public.products), false)
-- use sequence for the target column
ALTER TABLE public.products ALTER COLUMN id SET DEFAULT nextval('public_products_id_seq');
Run Code Online (Sandbox Code Playgroud)
CREATE SEQUENCE和SETVAL的文档参考