PostgreSQL表共享序列值:序列定义与表关联技术疑问
问题描述
今日替负责SQL代码库的同事顶岗,本人无SQL相关经验。现有文件exp_impl.sql,代码如下:
create schema if not exists exp; grant usage on schema exp to public; create table exp.manifest ( -- id INT PRIMARY KEY; -- some attributes are defined below and omitted );
收到需求:在主键后添加default nextval('ids_id_seq'),并要求该表的id与result.ids表的id共享同一序列。修改后文件如下:
create schema if not exists exp; grant usage on schema exp to public; create table exp.manifest ( id INT PRIMARY KEY default nextval('ids_id_seq'); -- some attributes are defined below and omitted );
Bazel测试已通过,但未找到ids_id_seq的定义。疑问:
- 是否需要在此文件中创建该序列?
- 如何让此文件关联
result.ids表,是否需要引入类似头文件的内容?
解决方案
- 不需要在此文件创建
ids_id_seq序列:需求明确要求和result.ids表共享序列,说明这个序列已经由result.ids表的定义脚本创建(大概率在resultschema对应的SQL文件中),直接引用即可。 - SQL没有类似“头文件”的机制:要关联
result.ids表的序列,只需做好两点:- 引用序列时使用全限定名:把
nextval('ids_id_seq')改成nextval('result.ids_id_seq'),避免数据库因schema搜索路径问题找不到序列; - 确保执行该SQL的用户拥有
result.ids_id_seq序列的USAGE权限,否则运行时会触发权限错误。
- 引用序列时使用全限定名:把
- 修正语法错误:修改后的SQL里
id字段末尾用了分号;,但后续还有其他字段,应该改成逗号,,否则会触发语法错误:id INT PRIMARY KEY DEFAULT nextval('result.ids_id_seq'),
内容的提问来源于stack exchange,提问作者24n8
相关产品推荐
相关产品推荐

