Search code examples
mysqldatabaserelational

MySQL creating a database table query


I want to create a join table between two or more tables.

The tables are Student, and course.

Join table will be enrolled.

the business rule is that a student can only enroll in one course at a time.

I want to prevent a user from creating additional enrollments after making 1 enrollment in a course.

I am not sure what type of contraint this will be, or if its even possible.

Can anyone help?

thank you

note: I dont think it is possible to create a Primary key as the primary key of another table, ie the studentID of the student table. If i could I would. breaks the rules i think. This would be a foreign key which is not unique.

If the business rule should be ignored, and assume that a student naturally will only enroll in one course at a time.. maybe ill stop worrying...


Solution

  • You could create a unique index for the id_student but this provably will bring problems if a student try to register in other course later. You shoud include the id_course into the unique constraint.

    ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE(studentId, course_id)

    Other solution could be creating a Trigger.

    The trigger should be a "before insert" trigger. This one should serch for information related to the student in the table, if the table doesn´t has information then insert information, else do nothing.

    CREATE TRIGGER 'ONE_STUDENT_PER_COURSE' BEFORE INSERT ON 'Enrollments' FOR EACH ROW BEGIN DECLARE student_id INT; SELECT n.id_student INTO student_id FROM table_enrollments n

    `IF student_id IS NULL THEN
        /* I DON´T REALLY KNOW EXACTLY THE SINTAXIS FOR INSERTING DATA OF THE BEFORE INSERT FOR YOU VERSION OF MYSQL
        BUT TRY THIS ONE
        */
        INSERT INTO table_enrollments (student_id, course_id) SELECT student_id, course_id FROM inserted
    END IF;
    

    END; $$`