Search code examples
mysqlsqlrelationships

Confusion to form MySQL Primary & Foreign Key constraints


I'm bulding a website where instructors upload their courses and then publish them. I'm planning the database and i have a few questions in my mind. Consider the following tables:

instructors(id(PK), fullname, email, password, created, updated)
categories(id(PK), title, description, created, updated)
courses(id(PK), cat_id(FK), instructor_id(FK), title, description, created, updated)
lessons(id(PK), course_id(FK), title, description, duration, created, updated)

I have made basic relationships between said tables. Now the questions are:

  • I want to check the category of a particular lesson.
  • I want to check lessons belong to a particular category.

Would it be fine if i put category_id as a foreign key in lessons table? This way I will be able to lessons in a category by joining the tables. For a reverse relationship, i can also select the categoryby selecting the course.

Please help me out. Thanks in advance.


Solution

  • If a lesson has 0 or 1 "categories", then you can put category_id in lessons. That is appropriate and correct.

    If a lesson could have multiple categories, then you need a junction table:

    create table lesson_categories (
        lesson_id . . .,
        category_id . . .,
        constraint fk_lesson_categories_lesson foreign key (lesson_id) references lessons(id),
        constraint fk_lesson_categories_category foreign key (category_id) references categories(id)
    );