三个表之间的唯一外键约束

Dou*_*las 4 postgresql foreign-key database-design

我想跟踪约会出席情况。访客可以预约,也可以直接出现。如果他们有约会,但错过了,在这种情况下,我想记录下错过约会的原因(如果知道)。

这些表格似乎涵盖了它:

appointments: id, visitor_id, scheduled_time
attendances: id, appointment_id, arrival_time
missed_appointments: id, appointment_id, reason
Run Code Online (Sandbox Code Playgroud)

我将如何添加约束,以便不能错过和参加约会?这个模式只是让它过于复杂吗?

A-K*_*A-K 5

我会用一张桌子来记录已完成和错过的约会。使用你的符号:

appointments: 
id, 
visitor_id, 
scheduled_time, 
status, 
CHECK(status in('Scheduled', 'Completed', 'Missed')), 
Reason_missed, 
CHECK((status='Missed' and reason_missed is not null) or (status<>'Missed' and reason_missed is null)), 
unique(id, status)

attendances: 
id, 
appointment_id (nullable), 
arrival_time, 
appointment_status,
check((appointment_id is null and appointment_status is null) or (appointment_id is not null and appointment_status in('Scheduled', 'Completed'),
foreign key(appointment_id, appointment_status) references appointments(id, status) on update cascade
Run Code Online (Sandbox Code Playgroud)