postgresql 中的关联表

Relationing tables in postresql

我想在我的 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;

我想在第一个 table 中添加外键,它将在字段 ID 上引用 table 图表。同样在第二个 table 中,我想添加外键,这将引用我上面创建的 table,anomaly_analysis 的 id 上的字段 anomaly_analysis_id,以及 chart_id 在 table 个图表和字段 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)
)
  • 您应该使用serial作为FK列。它应该是integer指向一个连续剧。
  • FK 的语法需要括号:.. REFERENCING table_name (column, column,...)
  • anomaly_analysis table 似乎是一个 junction table,实现了 n-m 关系。它肯定需要一个索引,甚至两个索引。
  • CREATE TABLE ... 的(子)语法非常庞大。见精manual

你可能想要这个:


CREATE TABLE charts( 
        id bigserial NOT NULL PRIMARY KEY
        );

CREATE TABLE anomaly_analysis(
   id bigserial NOT NULL PRIMARY KEY
   , chart_id bigint not null
         CONSTRAINT charts_fk REFERENCES charts (id)
   , analysis_date date NOT NULL
   );

CREATE TABLE anomaly_analysis_data_points(
   anomaly_analysis_id bigint NOT NULL
        CONSTRAINT anomaly_analysis_pk REFERENCES anomaly_analysis(id)
   , data_point_id bigint NOT NULL
        CONSTRAINT charts_fk REFERENCES charts(id)
-- , PRIMARY KEY (anomaly_analysis_id,data_point_id) -- ?? Will force an index to be created
-- , UNIQUE (data_point_id, anomaly_analysis_id) -- Will force an index to be created, too
   );

-- alter table data_series add column isAnomaly boolean; -- huh?