Adding foreign key columns to a MySQL table: step-by-step guide
Patricia Arquette
Patricia Arquette 2023-10-29 18:54:01
0
2
519

I have a table namedpayment_requestin MySQL

DESCRIBE payment_requestprovides the following output,

Theorderbooktable is provided below,

I want to add theidin thepayment_requesttable inorderbookas theidcolumn (second position) with the name after Foreign key topayment_request_id.

What is the SQL used to run MySQL?

Patricia Arquette
Patricia Arquette

reply all (2)
P粉395056196

You can do this when creating the table:

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

Or by changing the form:

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

Also seethis tutorial.

    P粉515066518

    First, you need to add a new column to the tableorderbook

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

    Then add a constraint that defines the foreign key

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

    refer to:

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!