foreign key

a foreign key in one table used to point primary key in another table.


1. first create a base table:

create table persons (

                                    id int primary key auto_increment,

                                    name varchar(20),

                                     age int);  

2. then insert the values for the base tables .


3. after that create the child table:

CREATE TABLE Orders (

    ->     OrderID int NOT NULL,

    ->     OrderNumber int NOT NULL,

    ->     PersonID int,

    ->     PRIMARY KEY (OrderID),

    ->     FOREIGN KEY (personID) REFERENCES Persons(ID)

    -> );


4. this will stop the orders table to insert the values into personid column , those does,nt exist in column id in the person table .


0 Comments