首页 > 解决方案 > 如何根据 postgres 中的另一列限制某些列的插入值

问题描述

我在这里有一张桌子,我想确保某些插入被阻止。

CREATE TABLE Creature (
  species TEXT,
  name TEXT,
  arms INTEGER,
  legs INTEGER
);

插入此表时,每个物种都应与具有相同物种的任何其他条目具有相同数量的手臂和腿。

INSERT INTO Creatures VALUES ('Human', 'John', 2, 2);
INSERT INTO Creatures VALUES ('Human', 'Steve', 2, 2);
INSERT INTO Creatures VALUES ('Human', 'Mark', 0, 4); -- should not work as humans have 2 arms and 2 legs

我曾尝试使用检查约束,但我不确定如何检查现有表值(如果它们已经存在)。

标签: postgresqlconstraints

解决方案


标准化。首先创建另一个表,在其中存储每个物种species的手臂和腿的数量。

CREATE TABLE species
             (id serial,
              name text,
              arms integer,
              legs integer,
              PRIMARY KEY (id));

然后只有一个外键引用creatures.

CREATE TABLE creature
             (id serial,
              species integer,
              name text,
              PRIMARY KEY (id),
              FOREIGN KEY (species)
                          REFERENCES species
                                     (id));

推荐阅读