Reputation: 1
Hello i am beginner in SQL and i have one question:
How to add new Column_B(int) which is foreign key to an existing Column_A(id) in same Table_A?
I tried this but i got Error Code: 1215. Cannot add foreign key constraint
ALTER TABLE Table_A ADD COLUMN Column_B int;
ALTER TABLE Table_A
ADD fk_Table_A FOREIGN KEY (Column_B) REFERENCES Table_A (Column_A);
Upvotes: 0
Views: 930
Reputation: 2678
alter table Table_A
ADD constraint fk_Table_A FOREIGN KEY (Column_B) REFERENCES Table_A (Column_A);
Upvotes: 2
Reputation: 775
It is possible that your references does not match. It can only add a foreign key when all the rows satisfy the foreign key condition, which is in your case that every value of Column_B
is in table_A.Column_A
.
Upvotes: 0