Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a foreign key column in the MySQL table?

Tags:

mysql

I have a table named payment_request in the MySQL and the

DESCRIBE payment_request provides the following output,

enter image description here

The oderbook table is provided below,

enter image description here

I want to add the id from the payment_request table in the orderbook as the foreign key with the name as payment_request_id after the id column (2nd position).

What will be the SQL to run the MySQL?

like image 307
Heisenberg Avatar asked Oct 16 '25 18:10

Heisenberg


2 Answers

First you need to add new column in table orderbook

ALTER TABLE orderbook
ADD payment_request_id INT(10) unsigned AFTER ID;

Then add a contraint that will define the foreign key

ALTER TABLE orderbook
ADD CONSTRAINT fk_orderbook FOREIGN KEY (payment_request_id) 
REFERENCES payment_request (id);

Reference:

  • MySQL Alter Table
like image 124
John Woo Avatar answered Oct 18 '25 07:10

John Woo


You can do this at table creation:

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
); 

or by altering the table:

ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID); 

Also refer to this tutorial.

like image 42
Mahi Parmar Avatar answered Oct 18 '25 07:10

Mahi Parmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!