Database choice for creating two connected tables?

前端 未结 3 1788
借酒劲吻你
借酒劲吻你 2021-01-25 07:24

I have to database tables \"Courses\" and \"Students\".

  • Courses table has columns (\"_id\", \"course_name\", \"course_number\").
  • Student table has column
相关标签:
3条回答
  • 2021-01-25 08:03

    There is m to n relationship between Courses and Students. To map a m to n relationship you need a third table.

    courses_students
    ----------------
    id_student
    id_course
    
    courses
    ----------------
    id_course
    // other fields
    
    students
    ----------------
    id_student
    // other fields
    
    0 讨论(0)
  • 2021-01-25 08:23

    Student (id, name, number) Course (id, name, number) StudentsCourses (student_id, course_id)

    You have to make a many to many relation.

    0 讨论(0)
  • 2021-01-25 08:24

    This is a classic case of many-to-many, and for that, you'll need a third table between Course and Student. The schema will look something like this:

    Course table has columns ("course_id", "course_name")

    Student_course table has columns ("student_id", "course_id");

    Student table as columns ("student_id", "student_name")

    Student_course table has foreign key constraints on both student and course tables.

    Example data:

    Course:

    id   |  name
    ------------------
    1    |  Maths
    2    |  English
    3    |  Science
    

    Student

    id   |  name
    ---------------
    1    |  Tom
    2    |  Dick
    3    |  Harry
    

    Student_course

    student_id | course_id
    ------------------------
    1          | 1
    1          | 2
    2          | 1
    3          | 3
    

    In this example, Student 1 (Tom) is on courses 1 and 2 (Maths, English),

    Student 2 (Dick) is on course 1 only (Maths)

    Student 3 (Harry) is on course 3 only (Science)

    0 讨论(0)
提交回复
热议问题