Many-to-many relations in RDBMS databases

后端 未结 3 1206
误落风尘
误落风尘 2020-12-18 05:35

What is the best way of handling many-to-many relations in a RDBMS database like mySQL?

Have tried using a pivot table to keep track of the relationships, but it lea

3条回答
  •  忘掉有多难
    2020-12-18 05:56

    I would use a pivot table, but I don't see where your issues are coming from. Using a simple student/class example:

    Student
    -------
    Id (Primary Key)
    FirstName
    LastName
    
    Course
    ------
    Id (Primary Key)
    Title
    
    StudentCourse
    -------------
    StudentId (Foreign Key -> Student)
    CourseId (Foreign Key -> Course)
    

    Or, as somebody else mentioned in response to your Student/Teacher/Course question (which would have an additional table to store the type of person in the course):

    PersonType
    ----------
    Id (Primary Key)
    Type
    
    Person
    ------
    Id (Primary Key)
    FirstName
    LastName
    Type (Foreign Key -> PersonType)
    
    Course
    ------
    Id (Primary Key)
    Title
    
    PersonCourse
    ------------
    PersonId (Foreign Key -> Person)
    CourseId (Foreign Key -> Course)
    

    The Student table contains student information, the Course table stores course information...and the pivot table simply contains the Ids of the relevant students and courses. That shouldn't lead to any null/empty columns or anything.

提交回复
热议问题