MySQL briefly introduces one-to-one, one-to-many, and many-to-many relationship processing methods

Example of a one-to-one relationship: one student corresponds to one student profile material, or each person has a unique ID number.
Example of a one-to-many relationship: A student belongs to only one class, but a college has multiple students.
Example of a many-to-many relationship: A student can select multiple courses, and a course also has multiple students.

These three kinds of relationships are processed and analyzed in the logical structure of the database:

1. One-to-many relationship processing:
We use the relationship between students and classes to illustrate the one-to-many relationship processing method.
Suppose there are existing basic tables student table (student number, name, ...), class table (class number, remark information, ...).

                       
Method 1:
Add a relationship table to represent the relationship between students and classes, and the relationship table contains fields (student ID, class ID). The class to which the student belongs is indicated by the correspondence between the student number and the class number.
Method 2:
Add a new field (class number) to the student table, which is associated with the class number in the class table as a foreign key of the student table. The value in the class number field of each student entity indicates the class the student belongs to.
Summary: In general, one-to-many relationships are handled by method two. Between two one-to-many entities, add a new field to the "many" entity table, which is the primary key of the "one" entity table.

2. Many-to-many relationship processing:

 

In a many-to-many relationship, we need to add a new relationship table. As in the above example, a course selection table is added to the student table and course table to represent the many-to-many relationship between students and courses. In the course selection table, the attributes that must be included are student ID and course ID. (Student ID, Course ID) This attribute set is just the keyword of the course selection table.





Reprint http://blog.csdn.net/lm709409753/article/details/48440401

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324885549&siteId=291194637