Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
sasori Avatar asked Feb 03 '10 13:02

sasori


People also ask

What is the use of reference keyword in MySQL?

The references keyword is used to define which table and column is used in a foreign key relationship. This means that a record in the hobby table must have a person_id that exists in the person table or else at the time of insert you will receive an error that the key does not exist.

How do you reference a table in MySQL?

We want to ensure that the orders table only contains orders of products that actually exist. So we define a foreign key constraint in the orders table that references the products table: CREATE TABLE orders ( order_id integer PRIMARY KEY, product_no integer REFERENCES products (product_no), quantity integer );

How do I use referential integrity in MySQL?

The only way you can enforce referential integrity in MySQL is by using a foreign key. This is an indexed column in a child table that refers to a primary key in a parent table. This is achievable if you design your tables with MySQL InnoDB database engine.


2 Answers

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)) 
like image 148
Håvard S Avatar answered Sep 20 '22 23:09

Håvard S


Here is an example directly from MySQL website:

CREATE TABLE parent (id INT NOT NULL,                      PRIMARY KEY (id) ) ENGINE=INNODB;  CREATE TABLE child (id INT, parent_id INT,                     INDEX par_ind (parent_id),                     FOREIGN KEY (parent_id) REFERENCES parent(id)                     ON DELETE CASCADE ) ENGINE=INNODB; 
like image 27
AJ. Avatar answered Sep 19 '22 23:09

AJ.