Foreign Keys are often a mystery to new DBAs in the MySQL world.
Hopefully this blog will clear some of this up.
In this example, we will have a table for employee data and a
table for the data on offices. First we need the two
tables.
CREATE TABLE employee (
-> e_id INT NOT NULL,
-> name CHAR(20),
-> PRIMARY KEY (e_id)
-> );
CREATE TABLE building (
-> office_nbr INT NOT NULL,
-> description CHAR(20),
-> e_id INT NOT NULL,
-> PRIMARY KEY (office_nbr),
-> FOREIGN KEY (e_id)
-> REFERENCES employee (e_id)
-> ON UPDATE CASCADE
-> ON DELETE CASCADE);
Those who do not use Foreign Keys will not be familiar with the
last four lines of the building table. The trick is that
there are two e_id columns, one in each table.
In the employee table …
[Read more]