After this, you can alter the first table to add the foreign key referencing the second table. Next, create the second table with its foreign key referencing the first table. In this case, you will need to create the first table without the foreign key. It is not possible to add the foreign key to the first table if the second table does not exist yet. Occasionally two tables may need to both contain a foreign key referencing the other table’s primary key. When creating a foreign key, the table being referenced must already exist, and the column being referenced needs to already have a primary key implemented. Teachers(TeacherID) refers to the Teachers table, containing the primary key column TeacherID. In this instance, TeacherID is the name of the column containing the foreign key in the Classes table. The following code creates a table containing a foreign key : CREATE TABLE Teachers (įOREIGN KEY (TeacherID) REFERENCES Teachers(TeacherID) To create a table with a FOREIGN KEY constraint, you denote the foreign key and the primary key that it references. How to declare a table with a foreign key in MySQL In an instance where a primary key in a table consists of multiple columns, the foreign key needs to refer to all of them.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |