What is a foreign key in MySQL?
A foreign key is a column in one table that points to the primary key of another table. It links the two tables and stops wrong values.
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
course_id INT,
FOREIGN KEY (course_id) REFERENCES courses(id)
);
Now a student cannot get a course_id that does not exist in courses, and a course that has students cannot be deleted by mistake. The tables must use InnoDB. See MySQL JOINs.
Learn more about the similar topics:
| Tutorials |
|---|
| MySQL Data Types |
| MySQL CREATE DATABASE |
| MySQL USE and SHOW DATABASES |
| MySQL DROP DATABASE |
| MySQL CREATE TABLE |
| MySQL Constraints |
| MySQL DROP TABLE |
| Exercises & Assignments |
|---|
| Write a query to get all column names of a database table |
| Write a query to create a new table with the data and structure of another table |