Skip to content

Instantly share code, notes, and snippets.

Created July 6, 2015 17:14
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save anonymous/79c2eed2a634777b16ff to your computer and use it in GitHub Desktop.
Save anonymous/79c2eed2a634777b16ff to your computer and use it in GitHub Desktop.
Many-to-many example
# For http://stackoverflow.com/a/7296873/396458
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
students:
id | first | last
=====================
1 | John | Lee
2 | Jane | Wilson
3 | Daniel | Gomez
classes:
id | name | teacher_id
==========================
1 | Biology | 2
2 | Physics | 4
3 | English | 77
student_classes
s_id | c_id
======================
1 | 2 # John is taking Physics
1 | 3 # John is taking English
2 | 2 # Jane is taking Physics
3 | 1 # Daniel is taking Biology
@Zer0SkiLL
Copy link

Can Daniel take Biology twice in student_classes table?

not if PK are being used. Fiddle here you can fiddle around and replace the last line with values (1, 1), (2, 2), (1, 1), (1,2);
it won't let you build the schema, since that would be a PK constraint violation.

@bingjiexiong
Copy link

for the student_classes case, can we create a schema without the PK? Cause I know PK must be unique.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment