[英]PostgreSQL custom CHECK on column
I have the following table:我有下表:
DROP TABLE IF EXISTS employees;
CREATE TABLE cars (
model VARCHAR (50),
brand VARCHAR (50),
price INTEGER
);
Which looks like the following:如下所示:
model brand price
Clio Renault 3000
Clio Renault 2700
Polo Volkswagen 4400
Golf Volkswagen 3400
I want to perform a CHECK
(or other) operation to guarantee that a model
cannot have multiple different brands
.我想执行
CHECK
(或其他)操作以保证一个model
不能有多个不同的brands
。 I am not sure how to insert information from another column when performing the check statement for model.在执行模型的检查语句时,我不确定如何从另一列插入信息。
You can enforce your constraint with one additional step of normalization :您可以通过一个额外的标准化步骤来强制您的约束:
CREATE TABLE car_model (
model text PRIMARY KEY
, brand text NOT NULL
);
CREATE TABLE car (
car_id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
, model text NOT NULL REFERENCES car_model
, price integer
);
Now, the PRIMARY KEY
constraint of car_model
enforces a single entry per model.现在,
car_model
的PRIMARY KEY
约束对每个模型强制执行一个条目。 And the FOREIGN KEY
constraint (with short notation REFERENCES ...
) enforces the same combination of model
and brand
every time.并且
FOREIGN KEY
约束(使用短符号REFERENCES ...
)每次都强制执行相同的model
和brand
组合。
To get your original representation, you might add a VIEW
like:要获得原始表示,您可以添加一个
VIEW
如:
CREATE VIEW AS
SELECT c.car_id, c.model, m.brand, c.price
FROM car c
JOIN car_model m USING (model);
You might do more.你可能会做得更多。 Like collect brands in a separate table ...
就像在单独的表格中收集品牌一样......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.