簡體   English   中英

外鍵 BIGSERIAL NULL Postgres

[英]Foreign key BIGSERIAL NULL Postgres

我無法在 POSTGRES 數據庫中插入記錄,我希望外鍵為空。

我的表:

CREATE TABLE sad_avaliado (
    id                BIGSERIAL NOT NULL,
    tenant_id         INT8 NOT NULL,
    funcionario_id    BIGSERIAL NOT NULL,
    epoca_id          BIGSERIAL NOT NULL,
    cca_id            BIGSERIAL,
    avaliador_id      BIGSERIAL NOT NULL,
    apagado           boolean NOT NULL,
    PRIMARY KEY (id)
 );
alter table sad_avaliado add constraint sad_funcionario_fkey foreign key (funcionario_id) references sad_funcionario;
alter table sad_avaliado add constraint sad_epoca_fkey foreign key (epoca_id) references sad_epoca;
alter table sad_avaliado add constraint sad_cca_fkey foreign key (cca_id) references sad_cca;
alter table sad_avaliado add constraint sad_avaliador_fkey foreign key (avaliador_id) references sad_avaliador;

我的 SQL 插入:

INSERT INTO public.sad_avaliado(
id, tenant_id, funcionario_id, epoca_id, cca_id, avaliador_id, apagado)
VALUES (1, 1, 1, 1, null, 1, false);

我的錯誤:

ERROR:  null value in column "cca_id" violates not-null constraint

bigserial用於自動增量的id列,它具有默認的“not null”並創建一個序列。

並且你不應該在insert語句中指定你的id,因為它是作為默認值插入nextval()

看這個例子

    test=# create table test01 ( id bigserial );
    CREATE TABLE
    test=# \d test01*
                                Table "public.test01"
     Column |  Type  | Collation | Nullable |              Default               
    --------+--------+-----------+----------+------------------------------------
     id     | bigint |           | not null | nextval('test01_id_seq'::regclass)

                           Sequence "public.test01_id_seq"
      Type  | Start | Minimum |       Maximum       | Increment | Cycles? | Cache 
    --------+-------+---------+---------------------+-----------+---------+-------
     bigint |     1 |       1 | 9223372036854775807 |         1 | no      |     1
    Owned by: public.test01.id

BIGSERIAL的外鍵引用應該使用BIGINT

CREATE TABLE sad_avaliado (
    id                BIGSERIAL NOT NULL,
    tenant_id         INT8 NOT NULL,
    funcionario_id    BIGINT NOT NULL,
    epoca_id          BIGINT NOT NULL,
    cca_id            BIGINT,
    avaliador_id      BIGINT NOT NULL,
    apagado           boolean NOT NULL,
    PRIMARY KEY (id)
 );

我認為這是外鍵引用應該與主鍵具有相同類型的概念的一個例外。 我的意思是,底層類型是相同的 ,但BIGSERIAL用於指定它是自動遞增(其他數據庫使用單獨的關鍵字,如auto_incrementidentity )。

使用bigint而不是bigserial

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM