add constraint fk
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
add constraint fk
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
foreign key in sql
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.
Example:
# creating table users
CREATE TABLE users(
user_id INT NOT NULL,
user_name VARCHAR(64) NOT NULL,
user_pass VARCHAR(32) NOT NULL,
PRIMARY KEY(user_id);
);
# adding user data
INSERT INTO users VALUES(1,"Raj","raj@123");
# creating table orders
CREATE TABLE orders(
order_id INT NOT NULL,
order_description VARCHAR(255),
orderer_id INT NOT NULL,
PRIMARY KEY(order_id),
FOREIGN KEY (orderer_id) REFERENCES users(user_id)
);
# adding order data
INSERT INTO orders VALUES(1,"Daily groceries",1);
add column mysql with foreign key
ALTER TABLE `TABLE_NAME`
ADD COLUMN `COLUMN_NAME` BIGINT(20) UNSIGNED NULL DEFAULT NULL AFTER `AFTER_COLUMN_NAME`,
ADD FOREIGN KEY `FOREIGN_RELATION_NAME`(`COLUMN_NAME`) REFERENCES `FOREIGN_TABLE`(`FOREIGN_COLUMN`) ON UPDATE SET NULL ON DELETE SET NULL
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us