SQL and ERD
SQL and ERD
Entity Relationship Diagram(ERD) can help us design databases. That is, to design a database, we can firstly create ERDs then convert these ERDs to tables. ERD uses so-called the Crow’s Feet Notation
to define how two entities(tables) are related.
There are several kinds of relationships between two entities.
One to Many Relation
One example of one-to-many relationship is as follows, i.e., a building contains many rooms:
1 | CREATE TABLE Building |
Note that in this case Room
is a weak entity, which means it must use a foreign key in conjunction with its attributes to create a primary key.
Many to Many Relation
One example of many-to-many relationship is as follows, i.e., one actor acts in many movies, and one movie has many actors:
1 | CREATE TABLE Film |
In this case, we use a weak entity ActorRole
as an associative table, which transforms the many-to-many relationship into two one-to-many relationships. In another word, we can replace a many-to-many relationship with an associate entity and two one-to-many relations.
Self Identifying Relation
A self identifying(self referencing) relationship is the relationship between an Entity and itself. For example, in school some courses are prerequisites for other courses:
1 | CREATE TABLE Course |