Relationships

Overview

Relational Cardinality

One to One

ALTER TABLE curriculeon.teacher_meta ADD teacher_id int NOT NULL;
CREATE UNIQUE INDEX teacher_meta_teacher_id_uindex ON curriculeon.teacher_meta (teacher_id);
ALTER TABLE curriculeon.teacher_meta
ADD CONSTRAINT teacher_meta_teachers_id_fk
FOREIGN KEY (teacher_id) REFERENCES teachers (id);

One to Many

ALTER TABLE curriculeon.assignments ADD teacher_id INTEGER NULL;
ALTER TABLE curriculeon.assignments
ADD CONSTRAINT teacher___fk
FOREIGN KEY (teacher_id) REFERENCES teachers (id);

Many to Many

Considering The Design Decisions

Assessing The Design Decisions

Defining the Schema

CREATE TABLE curriculeon.assignment_student
(
    assignment_id INTEGER NOT NULL,
    student_id INTEGER NOT NULL,
    CONSTRAINT students__fk FOREIGN KEY (student_id) 
    	REFERENCES students (id),
    CONSTRAINT assignments___fk FOREIGN KEY (assignment_id) 
    	REFERENCES assignments (id)
);
CREATE UNIQUE INDEX assignment_id_student_id_uindex
	ON curriculeon.assignment_student (assignment_id, student_id);

Joins

Joins - One to One

SELECT t.first_name, t.last_name, tm.years FROM
  curriculeon.teachers t
JOIN curriculeon.teacher_meta tm
  ON t.id = tm.teacher_id;
first_name last_name years
John Smith 4
Tabitha Schultz 4
Jane Herman 11

Joins - One to Many

SELECT t.first_name, t.last_name, a.name, a.URL
FROM curriculeon.teachers t
JOIN curriculeon.assignments a
  ON t.id = a.teacher_id;
first_name last_name name URL
Jane Herman Pokemon Lab https://github.com/Zipcoder/PokemonSqlLab
Jane Herman Poll App https://github.com/Zipcoder/CR-MacroLabs-Spring-QuickPollApplication
Tabitha Schultz Sum or Product https://github.com/Zipcoder/ZCW-MicroLabs-JavaFundamentals-SumOrProduct

Joins - Many to Many

SELECT s.name, a.name
FROM curriculeon.students s
JOIN curriculeon.assignment_student a_s
  ON a_s.student_id = s.id
JOIN curriculeon.assignments a
  ON a_s.assignment_id = a.id;
name name
Linnell McLanachan Pokemon Lab
Lorianna Henrion Pokemon Lab
Corena Edgeson Pokemon Lab
Archaimbaud Lougheid Pokemon Lab
Dun Pettet Pokemon Lab
Hymie Parrington Pokemon Lab
Linnell McLanachan Poll App