postgresql - 如何根据 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
我曾尝试使用检查约束,但我不确定如何检查现有表值(如果它们已经存在)。
解决方案
标准化。首先创建另一个表,在其中存储每个物种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));
推荐阅读
- node.js - 使用多个目录时出现 Node Js 目录错误 - ENOENT
- database-connection - 连接将被关闭,但有一个活动事务
- javascript - d3 bar label on grouped chart bar
- python - 需要作业生成器从列表中输出两个项目
- alibaba-cloud - 无法从nodejs触发邮件到阿里云直邮?
- broadleaf-commerce - 阔叶管理员允许装饰目标集合中的非唯一添加
- vector - 如何在 UWP 中通过 c# 代码更改 Canvas.Zindex 属性
- php - 如何使用相同的密码将 Laravel 用户验证为 wordpress 用户
- javascript - 数组中按字段的项目长度
- node.js - Node.js - Axios - 将文件上传到另一台服务器