0

How can you create a foreign key and link 2 tables?

21st Nov 2017, 7:36 PM
Ledia
Ledia - avatar
3 odpowiedzi
+ 1
are the "user_id" and "comment_id" the primary keys for each tables? because I am not getting it because when I enter this command it says that the foreign key constraint is formed incorrectly
23rd Nov 2017, 2:46 PM
Ledia
Ledia - avatar
0
Sorry, I did not realize that my initial answer was wrong. I made a working example and tested it on MySQL server version 5.7.20: CREATE DATABASE db_test; USE db_test; CREATE TABLE tbl_user ( -- Primary key id int PRIMARY KEY NOT NULL AUTO_INCREMENT, -- Some other attributes firstname varchar(100) NOT NULL, lastname varchar(100) NOT NULL ); CREATE TABLE tbl_comment ( -- Primary key id int PRIMARY KEY NOT NULL AUTO_INCREMENT, -- Foreign key user_id int NOT NULL, -- Some other attributes headline varchar(50) NOT NULL, content varchar(255) NOT NULL ); -- Set the foreign key constraint ALTER TABLE tbl_comment ADD CONSTRAINT fk_user_comment FOREIGN KEY (user_id) REFERENCES tbl_user (id); I hope this example is more clear.
23rd Nov 2017, 4:49 PM
Niklas Vogel
0
i typed this exactly but unfortunately it didn't work again. thank u tho
23rd Nov 2017, 6:47 PM
Ledia
Ledia - avatar