1

只是好奇,如果我有这张桌子:

CREATE TABLE "post" (
    "id" SERIAL,
    "revision" INTEGER NOT NULL DEFAULT 0,
    "summary" CHARACTER VARYING NOT NULL,
    "description" TEXT NOT NULL,
    "user_id" INTEGER NOT NULL
        REFERENCES "user" ("id") MATCH FULL
            ON UPDATE CASCADE
            ON DELETE RESTRICT,
    "post_type_id" INTEGER NOT NULL
        REFERENCES "post_type" ("id") MATCH FULL
            ON UPDATE CASCADE
            ON DELETE RESTRICT,
    "ctime" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    PRIMARY KEY("id", "revision")
);

存储帖子,这个表:

CREATE TABLE "post_state" (
    "post_id" INTEGER NOT NULL,
    "assembly_seat_id" INTEGER NOT NULL
        REFERENCES "assembly_seat" ("id") MATCH FULL
            ON UPDATE CASCADE
            ON DELETE RESTRICT,
    PRIMARY KEY("post_id")
);

我希望我的post_id领域指向post(id),我该怎么做?我尝试过使用以下短语:

    "post_id" INTEGER NOT NULL UNIQUE,
        REFERENCES "post" ("id") MATCH SIMPLE
            ON UPDATE RESTRICT
            ON DELETE RESTRICT,

但我收到此错误:

错误:引用表“post”的给定键没有唯一约束匹配

在这种情况下, 的值post_state(asembly_seat_id)不会改变。

4

1 回答 1

4

外键约束可以跨越多个列。您可以将列添加revision到表中post_state

CREATE TEMP TABLE post (
  post_id serial NOT NULL
 ,revision integer NOT NULL DEFAULT 0
 ,summary text NOT NULL
 ,description text NOT NULL
 ,user_id integer NOT NULL
    REFERENCES user (id) MATCH FULL ON UPDATE CASCADE ON DELETE RESTRICT
 ,post_type_id integer NOT NULL
    REFERENCES post_type (id) MATCH FULL ON UPDATE CASCADE ON DELETE RESTRICT
 ,ctime timestamptz DEFAULT NOW()
 ,PRIMARY KEY(post_id, revision)
);

CREATE TEMP TABLE post_state (
  post_id integer NOT NULL
 ,revision integer NOT NULL
 ,assembly_seat_id integer NOT NULL
    REFERENCES assembly_seat (id) MATCH FULL ON UPDATE CASCADE ON DELETE RESTRICT
 ,PRIMARY KEY(post_id, revision)
 ,FOREIGN KEY (post_id, revision) REFERENCES post (post_id, revision)
);

阅读有关外键约束的手册。

我正在使用post_idtable 的主键列的名称post。不要id用作列名。如果你加入一堆表,你最终会得到一堆所有名称的列id。遗憾的是,一些半笨的 ORM 习惯于这样做。

或者,最好的设计是在表中具有唯一post_idpost性并添加一个post_revision与 .1 关系的表post

于 2013-05-09T23:08:11.947 回答