简体   繁体   中英

SQL Autoincrement on Foreign key (MySQL)

I have a table called "Address" it reference to the table "Member", Address has a column called "id" , this column is a foreignkey. I forgot to add a autoincroment on this column.

Member:

  • id
  • name
  • lastname
  • ....
  • address_id (foreignkey)

Address:

  • id (this should be autoincreoment)
  • street
  • number
  • place
  • zipcode

when i try in sql

ALTER TABLE Address MODIFY COLUMN id INT auto_increment;

it throughs an error:

Error Code: 1833. Cannot change column 'id': used in a foreign key constraint 'fk_Member_Address1' of table 'mydb.member'

首先,您必须删除外键约束,然后更改名称并重新创建约束。

Try to fire these queries in sequence:

  1. ALTER TABLE Member DROP FOREIGN KEY address_id ;

  2. ALTER TABLE Address MODIFY COLUMN id INT auto_increment;

  3. ALTER TABLE Member ADD FOREIGN KEY ( address_id ) REFERENCES Address( id );

Here you first remove foreign key constraint from member table, then add auto_increment to address table and then again add foreign key constraint to member table.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM