Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Adding a constraint foreign key to existing column
I've been playing around with what I have learned in the database foundations. In the video, we are showed how to add a constraint with foreign key referencing another table when adding a new column.
ALTER TABLE table_name ADD COLUMN column_name INTEGER, ADD CONSTRAINT FOREIGN KEY (column_name) REFERENCES table_name(column_name);
What if the column already exists and there are several thousand of results in it?
I have tried a few things, example:
Used these 3 beginnings: ALTER TABLE table_name1 MODIFY COLUMN column_name1 ALTER TABLE table_name1 ALTER COLUMN column_name1
Followed it with: BIGINT(20) NOT NULL, ADD CONSTRAINT FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2);
BIGINT(20), ADD CONSTRAINT FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2);
ADD CONSTRAINT FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2);
Nothing seems to work. The latest test I did was : ALTER TABLE xtable ADD CONSTRAINT FOREIGN KEY (xcolumn) REFERENCES ytable(ycolumn);
I get this error:
1452 - Cannot add or update a child row: a foreign key constraint fails (
#sql-62d4_390709_ibfk_1 FOREIGN KEY (
Can anyone enlighten me on what I'm doing wrong?