how to create 3 foreign key in sql code example

Example 1: sql foreign key

# A foreign key is essentially a reference to a primary
# key in another table.

# A Simple table of Users, 
CREATE TABLE users(
	userId INT NOT NULL,
  	username VARCHAR(64) NOT NULL,
  	passwd VARCHAR(32) NOT NULL,
  	PRIMARY KEY(userId);
);
# Lets add a LEGIT user!
INSERT INTO users VALUES(1000,"Terry","Teabagface$2");

# We will create an order table that holds a reference
# to an order made by our Terry
CREATE TABLE orders(
	orderId INT NOT NULL,
  	orderDescription VARCHAR(255),
  	ordererId INT NOT NULL,
  	PRIMARY KEY(orderId),
  	FOREIGN KEY (ordererId) REFERENCES users(userId)
);
# Now we can add an order from Terry
INSERT INTO orders VALUES(0001,"Goat p0rn Weekly",1000);

# Want to know more about the plight of Goats?
# See the link below

Example 2: foreign key mssql

CREATE TABLE Sales.TempSalesReason 
   (
      TempID int NOT NULL, Name nvarchar(50)
      , CONSTRAINT PK_TempSales PRIMARY KEY NONCLUSTERED (TempID)
      , CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID)
        REFERENCES Sales.SalesReason (SalesReasonID)
        ON DELETE CASCADE
        ON UPDATE CASCADE
   )
;

Tags:

Php Example