So I've tried to do this a number of ways. Basically I'm given the following instructions:
Using the blog database (use either a single-line or a multi-line SQL statement):
Write a SQL ALTER TABLE statement that adds a post_id column to the blog.comments table. This new column should be an INTEGER data type with a max. size of 3 digits, UNSIGNED, it should be NOT NULL and it should work as a FOREIGN KEY that uses as a reference the id column of the blog.posts table.
I have no issue adding the column, it's getting the foreign key to work that's stumping me. I used the following code:
ALTER TABLE blog.comments
ADD COLUMN post_id INT(3) UNSIGNED NOT NULL;
ALTER TABLE blog.comments
ADD FOREIGN KEY (post_id) REFERENCES posts(id);
And I keep getting the following error when I submit it:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (
b log
.#sql-628_2a
, CONSTRAINT#sql-628_2a_ibfk_1
FOREIGN KEY (post_id
) REFERENCESposts
(id
))
I have tried several different versions but I can't get it to work.