Can uniqueness be switched on or off depending on another constraint or other variable within a table

StackOverflow https://stackoverflow.com/questions/20572373

  •  01-09-2022
  •  | 
  •  

Question

I’m new to SQL so please forgive if my terminology is a little out. I’m using phpMyAdmin v3.4 and MySQL (server version) v5.5, I’m building a simple database (only 3 or 4 tables) as a goodwill gesture for my golf club that allows a member to sign-up to play in competitions held on a Saturday or Sunday. The Member may play on both days if they wish (and if they have the energy!) but they may only play once a day. Tables are:

MEMBERS: memberName, memberID

TEE_TIMES: day (choice of Saturday or Sunday), time

BOOKINGS: day_FK, time_FK, memberID_FK, bookingRef

Problem I have with the BOOKINGS table is that I currently have memberID_FK as unique which is fine 95% of the time as most members would play on one day or the other and hence they would only appear in the table once. However, there will be the odd member who will wish to play on “both” days. I could get around this by having 2 BOOKINGS tables (rather than 1), e.g. BOOKINGS_SATURDAY and a separate table for BOOKINGS_SUNDAY, however I believe that would be bad practice and inefficient as I’d have 2 identical table structures (albeit with different names) to manage rather than 1.

I guess what I’m asking is can (memberID_FK) uniqueness be switched on or off depending on another constraint or other variable within a table (in this case the day of choice) - perhaps some kind of clever / dynamic relation between memberID_FK and day_FK? I’d rather implement this as a SQL table structure as I’m not yet familiar with coding although, I’m totally open to a different way of achieving the end goal e.g. splitting the table further (rather than duplicating the structure).

Was it helpful?

Solution

Use a composite unique key:

CREATE TABLE Bookings
...
UNIQUE KEY member_day (memberID_FK, day_FK)

OTHER TIPS

FK are not unique, they usually are on the many side of a one - many relationship.

Make a unique key across member_id and day (maybe even include time ?)

The PK (in your case the memberID from the members table and the day from the tee times table) should be unique, But the FK side is ok not to be unique

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top