外键SQL上的postgreCircle一致性



我有三个表

aircrafts 
flights
events 

flight有外键aircraft_id

event也有外键aircraft_id可选外键flight_id

是否有方法对events进行约束,以确保如果flight_id不为NULL,则event上的aircraft_id与具有此flight_idflight上的aircraft_id相同?

这取决于基本的业务规则。是不是";不存在需要不需要飞行的飞机的事件";。如果是这种情况,那么只需从事件中删除aircraft_id。然而,这似乎不太可能,即维护活动不需要飞行。因此,将规则重述为";事件需要飞行或飞机";。在事件中使aircraft_id和flight_id都是可选的,然后创建一个检查约束,要求其中一个为null,另一个不为null。

create table events
( event_id integer generated always as identity  
, aircraft_id  integer
, flight_id integer
, constraint events_pk primary key(event_id)
, constraint event2aircraft_fk
foreign key (aircraft_id)
references aircraft(aircraft_id)
, constraint event2flight_fk
foreign key (aircraft_id)
references aircraft(aircraft_id) 
, constraint event_or_aircraft_ck
check (   (aircraft_id is null and flight_id is not null)  
or (aircraft_id is not null and flight_id is null)
)
)
; 

现在,当事件需要飞行时,只能从飞行中检索aircraft_id。

您需要添加两个约束

ALTER table flights ADD constraint uniq_id_aircraft_id unique (id, aircraft_id);
ALTER table events ADD FOREIGN KEY (aircraft_id, flight_id) REFERENCES event_flights (aircraft_id, id);

得到你想要的

最新更新