What is the best way to create a one-to-one relationship between these two tables?
Here is the ER Diagram
Here is the SQL statement for the Athlete table but I'm still not sure how to create the DressingRoom table
CREATE TABLE Athlete
(
StudentID INT NOT NULL,
FirstName VARCHAR(15) NOT NULL,
LastName VARCHAR(15) NOT NULL,
Gender VARCHAR(9),
Eligibility VARCHAR(15),
CONSTRAINT AthletePK PRIMARY KEY (StudentID),
CONSTRAINT GenderCheck CHECK (Gender IN ('Male', 'Female')),
CONSTRAINT EligibilityCheck Check (Eligibility IN ('Eligible', 'NotEligible'))
);
This does look like a 1-N relationship, where each athlete may have 0 to N lockers.
Here are typical DDL statements for this schema:
create table athlete (
studentID int primary key,
firstName varchar(50),
lastName varchar(50),
gender varchar(5),
eligibility varchar(50)
);
create table dressingRoom (
lockerNumber int,
studentID int references athlete(studentID),
lockerBuilding varchar(50),
primary key (studentID, lockerNumber)
);
The important thing is that you want a foreign key on dressingRoom(studentID )
that references athlete(studentID)
.
If you want a 1-1 relationship, meaning that each student may only have one locker, then you can use lockerNumber
as a primary key, and set a unique
constraint on studentId
(or the other way around):
create table dressingRoom (
lockerNumber int primary key,
studentID int references athlete(studentID) unique,
lockerBuilding varchar(50),
);
Note that in that case, it makes little sense to create two tables. You can store the lockerNumber
directly in athelete
, with a unique
constraint:
create table athlete (
studentID int primary key,
firstName varchar(50),
lastName varchar(50),
gender varchar(5),
eligibility varchar(50),
lockerNumber int unique
);