سؤال

I have a table like that:

CREATE TABLE `Appointment` (
    id INT NOT NULL AUTO_INCREMENT,
    user_id INT NOT NULL,
    doctor_slot_id INT NOT NULL,
    date DATE NOT NULL,
    PRIMARY KEY(id),
    FOREIGN KEY(user_id) REFERENCES user(id),
    FOREIGN KEY(doctor_slot_id) REFERENCES doctor_slot(id)
);

I want that a user can't arrange an appointment with a doctor more than once in a day. So I want to add a unique constraint between doctor_id and user_id but in this structure I can't. I tried those things which are not in SQL syntax:

UNIQUE(user_id, doctor_slot.doctor_id)

and

UNIQUE(user_id, doctor_slot(doctor_id))

and

UNIQUE(user_id, doctor_id(doctor_slot))

But as you know, they didn't work. Are there any suggestions you can make?

هل كانت مفيدة؟

المحلول

Based on your comment about the what the doctor_slot is, it would seem you have a bit on an issue with your schema design. There should be no reason for you to store both a slot_id and a date in the appointment table, in that the doctor_slot already has a date component, so storing the date in the appointment table is a redundant storage of data, and could become problematic to keep in sync.

Of course, without the date on this table it is impossible to force a unique constraint in the database for this table.

My recommendation for any type of calendar-based app like this, would be to first create a date table. I usually use a script like the one here: http://www.dwhworld.com/2010/08/date-dimension-sql-scripts-mysql/ to create this date table. Having such a table can allow you to use a simple date_id to reference all kinds of different information about a date (this is a technique commonly used in data warehouses). As long as you use this date_id in all the other tables where you need dates, it as extremely simple to look of dates in any fashion you desire (by day of week, month, week number, whether it is a weekday or not, etc.).

You could use a similar concept to build your timeslots. Maybe make a table that has 96 entries (24 hours * 15 minutes) to represent 15 minute intervals - obviously you can change this to whatever interval you like.

You could then build your appointment table like this:

appointment_id
user_id
doctor_id
date_id
time_start_id <= time slot for appointment start
time_end_id <= time slot for appointment end

Id don't see separate need for a doctor_slots table here. If you want to track open doctor slots, you could also do that in this table by having user_id simply = NULL until the slot is filled.

This would allow you to enforce unique index on user_id and date_id.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top