What is the method for creating foreign keys in MySQL?

The method of creating a foreign key in MySQL is as follows:

When creating a table, specify a foreign key constraint. For example, if we have two tables, one is the students table and the other is the courses table. We want to add a foreign key in the students table, linking it to the course_id field in the courses table. You can use the following statement to create the students table and add a foreign key constraint:

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(50),
    course_id INT,
    FOREIGN KEY (course_id) REFERENCES courses(course_id)
);

Add a foreign key constraint to an existing table. If two tables already exist and do not have a foreign key constraint, you can use the following statement to add a foreign key constraint:

ALTER TABLE students
ADD CONSTRAINT fk_course
FOREIGN KEY (course_id) REFERENCES courses(course_id);

This will allow you to create a foreign key in the students table, linking it to the course_id field in the courses table. It is important to note that in order to successfully create the foreign key, the data types of the two linked fields must match.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds