sasori sasori - 3 months ago 8
MySQL Question

How to use the keyword 'references' in MySQL?

How is the

references
keyword used when creating a table?

Let's say I want to create two tables
person
and
hobby
and I want the hobby table id to reference the id of person?

person table
- id
- name

hobby
- id
- person_id
- hobby_name


How do I do that?

Answer

Create the hobby table similarly to this:

CREATE TABLE hobby (
  id INT NOT NULL AUTO_INCREMENT,
  person_id INT NOT NULL,
  hobby_name VARCHAR(255),
  PRIMARY KEY(id),
  FOREIGN KEY(person_id) REFERENCES person(id))