In: Computer Science
Create a table in SQL with foreign key reference:
1.Create the three tables without any columns
2.Alter the tables to add the columns
3.Alter the tables to create the primary and foreign keys
SQL statements-->
1->
create 3 empty tables ->
CREATE TABLE TABLE1("\0");
CREATE TABLE TABLE2("\0");
CREATE TABLE TABLE3("\0");
These 3 statements will create 3 table with 0 columns and records.
CREATE is used to create
TABLE is used to give table name
TABLE1 is table name
\0 is used to set 0 columns.
2-->
to add columns to a table -->
ALTER TABLE TABLE1 ADD FirstName varchar(55);
ALTER TABLE Table1 ADD ID integer(5);
ALTER TABLE Table1 ADD orderID integer(5);
now for table 2 -
ALTER TABLE TABLE2 ADD FirstName varchar(55);
ALTER TABLE Table2 ADD ID integer(5);
ALTER TABLE Table2 ADD orderID integer(5);
same for table 3
3 -->
now we add primary and foreign key -->
ALTER TABLE TABLE1 ADD CONSTRAINT PK_Person PRIMARY KEY (ID);
ALTER TABLE TABLE2 ADD CONSTRAINT PK_Person PRIMARY KEY (orderID);
ALTER TABLE TABLE1 ADD FOREIGN KEY (orderID) REFERENCES TABLE2(orderID);
like this we can add primary and foreign keys