HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Unique foreign key constraint between three tables

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
threeuniquetablesforeignbetweenconstraintkey

Problem

I'd like to track appointment attendances. Visitors can have appointments, or they can just turn up. If they have an appointment, and miss it, in which case I'd like to record a reason for the missed appointment, if known.

These tables seem to cover it:

appointments: id, visitor_id, scheduled_time
attendances: id, appointment_id, arrival_time
missed_appointments: id, appointment_id, reason


How would I add a constraint such that an appointment can't be missed and attended? Is this schema just overcomplicating it?

Solution

I would use one table for both completed and missed appointments. Using your notation:

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

Code Snippets

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

Context

StackExchange Database Administrators Q#24498, answer score: 5

Revisions (0)

No revisions yet.