Can anyone explain how to implement one-to-one, one-to-many and many-to-many relationships while designing tables with some examples?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- php PDO::FETCH_ASSOC doesnt detect select after ba
- Bulk update SQL Server C#
One-to-one: Use a foreign key to the referenced table:
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
Many-to-many: Use a junction table (example):
Example queries:
Here are some real-world examples for the types of relationships:
1:1
A relationship is one to one if and only if one record from table A is related to a maximum of one record in a table B.
To establish a one to one relationship, the primary key of table B (with no orphan record) must be the secondary key of the table A (with orphan records).
For example:
1:M
A relationship is one to many if and only if one record from table A is related to one or more records in table B. However, one record in table B can not be related to more one record in table A.
To establish a one to many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).
For example:
M:N
A relationship is many to many if and only if one record from table A is related to one or more records in table B and vice-versa.
To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the the primary keys of both table A and table B.
One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.