02 Database Design Many To Many
02 Database Design Many To Many
Charles Severance
www.pg4e.com
http://www.pg4e.com/lectures/02-Database-Design-Many-to-Many.txt
Relational Database Design
http://en.wikipedia.org/wiki/Relational_model
Database Design
• Database design is an art form of its own with particular skills and
experience.
• Our goal is to avoid the really bad mistakes and design clean and
easily understood databases.
• Basic Rule: Don’t put the same string data in twice - use a relationship
instead
• When there is one thing in the “real world” there should only be one
copy of that thing in the database
Track Len Artist Album Genre Rating Count
For each “piece of info”...
• Is the column an object or an Len Album
attribute of another object? Genre
belongs-to
Genre
Key Terminology
Finding our way around....
Three Kinds of Keys
• Primary key - generally an integer auto-
increment field Album
album_id
• Logical key - what the outside world uses title
for lookup
artist_id
• Foreign key - generally an integer key ...
pointing to a row in another table
Primary Key Rules
User
Best practices: user_id
email
•Never use your logical key as the primary key.
password
name
•Logical keys can and do change, albeit slowly.
created_at
modified_at
•Relationships that are based on matching string
login_at
fields are less efficient than integers.
Foreign Keys
Album
• A foreign key is when a table has a Artist
album_ id
column containing a key that points to artist_id
title
the primary key of another table. name
artist_id
...
...
• When all primary keys are integers,
then all foreign keys are integers. This
is good - very good.
Normalization
and Foreign Keys
We want to keep track of which band is the “creator” of each music track...
What album does this song “belong to”?
• Add a special “key” column to each table, which you will make
references to.
http://en.wikipedia.org/wiki/Database_normalization
Integer Reference Pattern
We use integer columns in one music=> SELECT * FROM artist;
table to reference (or look up) id | name
rows in another table. ----+-------------
1 | Led Zeppelin
2 | AC/DC
music=> SELECT * FROM album;
id | title | artist_id
----+--------------+-----------
1 | Who Made Who | 2
2 | IV | 1
Building a Physical Data Schema
Track
Artist
belongs-to Rating
Len
Album Count
belongs-to
belongs-to
Genre
belongs-to Track
Album Title
Rating
Len Track
Count
id
Album title
Table rating
id
Primary key len
Logical key title
Foreign key count
album_id
Artist Track
id Album id
name id title
title rating
artist_id len
Table
Primary key count
Logical key album_id
Foreign key Genre genre_id
Naming the Foreign key
id
artist_id is a convention name
Creating our Music Database
sudo -u postgres psql postgres
music=>
music=> INSERT INTO artist (name) VALUES ('Led Zeppelin');
INSERT 0 1
music=> INSERT INTO artist (name) VALUES ('AC/DC');
INSERT 0 1
music=> SELECT * FROM artist;
id | name
----+-------------
1 | Led Zeppelin
2 | AC/DC
(2 rows)
music=>
music=> INSERT INTO album (title, artist_id) VALUES ('Who Made Who', 2);
INSERT 0 1
music=> INSERT INTO album (title, artist_id) VALUES ('IV', 1);
INSERT 0 1
music=> SELECT * FROM album;
id | title | artist_id
----+--------------+-----------
1 | Who Made Who | 2
2 | IV | 1
(2 rows)
music=> INSERT INTO genre (name) VALUES ('Rock');
INSERT 0 1
music=> INSERT INTO genre (name) VALUES ('Metal');
INSERT 0 1
music=> SELECT * FROM genre;
id | name
----+-------
1 | Rock
2 | Metal
(2 rows)
music=> INSERT INTO track (title, rating, len, count, album_id, genre_id)
music-> VALUES ('Black Dog', 5, 297, 0, 2, 1) ;
INSERT 0 1
music=> INSERT INTO track (title, rating, len, count, album_id, genre_id)
music-> VALUES ('Stairway', 5, 482, 0, 2, 1) ;
INSERT 0 1
music=> INSERT INTO track (title, rating, len, count, album_id, genre_id)
music-> VALUES ('About to Rock', 5, 313, 0, 1, 2) ;
INSERT 0 1
music=> INSERT INTO track (title, rating, len, count, album_id, genre_id)
music-> VALUES ('Who Made Who', 5, 207, 0, 1, 2) ;
INSERT 0 1
music=> SELECT * FROM track;
id | title | len | rating | count | album_id | genre_id
----+---------------+-----+--------+-------+----------+----------
1 | Black Dog | 297 | 5| 0| 2| 1
2 | Stairway | 482 | 5| 0| 2| 1
3 | About to Rock | 313 | 5| 0| 1| 2
4 | Who Made Who | 207 | 5| 0| 1| 2
(4 rows)
music=> SELECT * FROM track;
id | title | len | rating | count | album_id | genre_id
----+---------------+-----+--------+-------+----------+----------
1 | Black Dog | 297 | 5| 0| 2| 1
2 | Stairway | 482 | 5| 0| 2| 1
3 | About to Rock | 313 | 5| 0| 1| 2
4 | Who Made Who | 207 | 5| 0| 1| 2 music=> SELECT * FROM genre;
id | name
----+-------
1 | Rock
music=> SELECT * FROM album; 2 | Metal
id | title | artist_id
----+--------------+-----------
1 | Who Made Who | 2
2 | IV | 1
music=> SELECT * FROM artist;
id | name
----+-------------
1 | Led Zeppelin
We Have Relationships!
2 | AC/DC
Using Join Across Tables
http://en.wikipedia.org/wiki/Join_(SQL)
Relational Power
• By removing the replicated data and replacing it with references to a
single copy of each bit of data, we build a “web” of information that
the relational database can read through very quickly - even for very
large amounts of data.
• Often when you want some data it comes from a number of tables
linked by these foreign keys.
The JOIN Operation
• The JOIN operation links across several tables as part of a SELECT
operation.
• You must tell the JOIN how to use the keys that make the connection
between the tables using an ON clause.
music=> SELECT * FROM album; music=> SELECT * FROM artist;
id | title | artist_id id | name
----+--------------+----------- ----+-------------
1 | Who Made Who | 2 1 | Led Zeppelin
2 | IV | 1 2 | AC/DC
• SET NULL – Set the foreign key columns in the child rows to null
http://stackoverflow.com/questions/1027656/what-is-mysqls-default-on-delete-behavior
Many-to-Many Relationships
www.tsugi.org
Review:
belongs-to Track One to Many
Album Title
One Many Rating
Len Track
Count
id
Table
Primary key Album title
Logical key One rating
Foreign key id
len
title Many
count
album_id
https://en.wikipedia.org/wiki/One-to-many_(data_model)
music=> SELECT * FROM track;
id | title | len | rating | count | album_id | genre_id
----+---------------+-----+--------+-------+----------+---------- One Many
1 | Black Dog | 297 | 5| 0| 2| 1
2 | Stairway | 482 | 5| 0| 2| 1 music=> SELECT * FROM genre;
3 | About to Rock | 313 | 5| 0| 1| 2 id | name
4 | Who Made Who | 207 | 5| 0| 1| 2 ----+-------
1 | Rock
2 | Metal
https://en.wikipedia.org/wiki/One-to-many_(data_model)
Many to Many
• Sometimes we need to model a
relationship that is many to many.
• We need to add a “connection”
table with two foreign keys.
• There is usually no separate
primary key.
member-of
User
Course
title Many Many email
name
student
course member id
id Many
student_id email
Many One
title One course_id name
role
https://en.wikipedia.org/wiki/Many-to-many_(data_model)
Start with a Fresh Database
CREATE TABLE student (
id SERIAL,
name VARCHAR(128),
email VARCHAR(128) UNIQUE,
PRIMARY KEY(id)
);
• By normalizing the data and linking it with integer keys, the overall
amount of data which the relational database must scan is far lower
than if the data were simply flattened out.
• The key is to have one copy of any data element and use relations and
joins to link the data to multiple places.
• This greatly reduces the amount of data that must be scanned when
doing complex operations across large amounts of data.