[英]My query proceeds when it should throw an error
So I am trying to validate a query所以我想验证一个查询
The below code, should throw an error.下面的代码,应该抛出一个错误。 Because VIN '2234' belongs to user with ID of 2, why it doesn't throw an error when I am trying to add this VIN to user with ID of 1?
因为 VIN '2234' 属于 ID 为 2 的用户,为什么当我尝试将此 VIN 添加到 ID 为 1 的用户时它不会引发错误?
Each car has an unique VIN and a client id.每辆车都有一个唯一的 VIN 和一个客户 ID。 Whenever I add a service with a specific
client
the client id
must match his VIN number.每当我向特定
client
添加服务时, client
client id
必须与他的 VIN 号匹配。
create table client (
id BIGSERIAL primary key,
name VARCHAR(20)
);
create table cars (
vin VARCHAR(20) not null unique primary key,
fk_client BIGSERIAL unique,
FOREIGN KEY (fk_client) references client(id)
);
create table service (
id BIGSERIAL primary key,
fk_client BIGSERIAL,
fk_vin VARCHAR(20),
FOREIGN KEY(fk_client) references cars(fk_client),
FOREIGN KEY(fk_vin) references cars(vin)
);
insert into client(name) values ('Jan');
insert into client(name) values ('John');
insert into cars (vin, fk_client) values ('223', 1);
insert into cars (vin, fk_client) values ('2234', 2);
insert into service (fk_client, fk_vin) values (1,'2234');//should throw error, because VIN 2234 doesn't belong to user with ID of 1.
When a service is for a car, we know the client, because the car row references a client row.当服务用于汽车时,我们知道客户,因为汽车行引用客户行。
So, if every service is for a car, there must be no client ID in the service table.因此,如果每个服务都是针对汽车的,那么服务表中一定没有客户端 ID。
The only reason for storing a client ID in the service table would be that there are not only services for cars, but also services for clients regardless of a car.将客户 ID 存储在服务表中的唯一原因是不仅有针对汽车的服务,而且还有针对与汽车无关的客户的服务。 In that case you'd either store the car ID or the client ID in the service table.
在这种情况下,您可以将汽车 ID 或客户端 ID 存储在服务表中。 What you don't want is a row with both a client and a car or neither a car nor a client.
您不想要的是同时有客户和汽车或既没有汽车也没有客户的争吵。 You can add a check constraint to ensure that always one of the IDs is set:
您可以添加检查约束以确保始终设置其中一个 ID:
ALTER TABLE service
ADD CONSTRAINT chk_service_ids
CHECK ( (fk_client IS NOT NULL AND fk_vin IS NULL) OR
(fk_client IS NULL AND fk_vin IS NOT NULL) );
So, depending on what you really want, either delete the client ID from the table or add the check constraint.因此,根据您的实际需要,从表中删除客户端 ID 或添加检查约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.