【发布时间】:2021-11-16 17:07:49
【问题描述】:
我想在我的 postgresql 数据库中建立一些关系。
我的脚本如下所示:
create table anomaly_analysis
(
id bigserial not null,
chart_id bigserial constraint charts_pk references charts id not null,
analysis_date date not null,
primary key (id)
);
create table anomaly_analysis_data_points
(
anomaly_analysis_id bigserial
constraint anomaly_analysis_pk
references anomaly_analysis id not null,
data_point_id bigserial
constraint charts_pk
references charts id not null
);
alter table data_series
add column isAnomaly boolean;
我想在第一个表中添加外键,它将在字段 id 上引用表图表。同样在第二个表中,我想添加外键,这将在我上面创建的表中引用,anomaly_analysis 的 id 上的字段 anomaly_analysis_id 以及表格图表和字段 id 上的 chart_id。
我试过这个查询(这是一行的例子):
chart_id bigserial constraint charts_pk foreign key (charts_id )references charts not null
但这对我也不起作用。我尝试了许多类似的组合,我正在阅读文档和其他网站,但没有奏效。我应该怎么做才能使我的脚本正确?
编辑
我忘记添加日志了。正在使用 flyway 为数据库提供服务。 我收到的例外是:
SQL State : 42601
Error Code : 0
Message : ERROR: syntax error at or near "id"
Position: 121
Location : db/migration /V1.1.15__add_anomaly_analysis_tables.sql (/mypath/V1.1.15__add_anomaly_analysis_tables.sql)
Line : 1
Statement : create table anomaly_analysis(
id bigserial not null,
chart_id bigserial constraint charts_pk references charts id not null,
analysis_date date not null,
primary key (id)
)
【问题讨论】:
-
您不应将序列用作 FK 列。它应该是一个整数,指向一个序列。
-
但是我项目中的其他列正在使用 fk 这样的大序列类型,让我想知道的是其他具有类似脚本的表工作正常,只是这个在初始化期间崩溃了。跨度>
-
序列号是一个整数,其默认值由函数提供。 FK 是一组列,引用另一个表中的一组列。将 FK 设置为生成器函数提供的某个值是没有意义的。生成器函数对另一个表一无所知。
-
chart_id bigint constraint charts_pk references charts (id) not nullpostgresql.org/docs/current/sql-createtable.html -
所以我只需要更改我创建的列的类型,以使我的表格正常工作吗?
标签: postgresql flyway