外键的循环一致性 SQL

Circle consistency on foreign keys SQL

我有三张表

aircrafts 
flights
events 

flight 有外键 aircraft_id

event 还有外键 aircraft_id可选 外键 flight_id

有没有办法对 events 进行约束以保证如果 flight_id 不为 NULL,则 event 上的 aircraft_idaircraft_id 相同在 flightflight_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);

得到你想要的

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

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 只能从飞行中检索。