简体   繁体   中英

How Do I Create One-to-One Relationship

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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM