Search code examples
mysqlprimary-keyauto-increment

Mysql alter a primary key column that has a relationship with another table


Could I change a primary key column that has a relationship in another table to be auto increment.

this is my code

 alter table sales_agreement modify column client_id int(11)  auto_increment ;

but I get error:-

 Cannot change column 'Client_id': used in a foreign key constraint 'Relationship5' of table ' order_sheet'

Edit Sales_Agreement Table

    CREATE TABLE  Sales_Agreement
    (

      Client_id Int NOT NULL,
      Client Varchar(200) NOT NULL,
     PRIMARY KEY (Client_id)
    ) ;

Table order_sheet

 CREATE TABLE Sales.Order_Sheet
(
  Client_id Int NOT NULL
)
;
ALTER TABLE Sales.Order_Sheet ADD PRIMARY KEY (Client_id)
;

ALTER TABLE Order_Sheet ADD CONSTRAINT Relationship5 FOREIGN KEY (Client_id) REFERENCES Sales_Agreement (Client_id)  
;

Solution

  • Try to drop foreign key first,

    ALTER TABLE 'Order_Sheet' DROP FOREIGN KEY 'Relationship5';

    and then alter table by modifying the primary key.