0
How can you create a foreign key and link 2 tables?
3 Antworten
+ 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
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.
0
i typed this exactly but unfortunately it didn't work again. thank u tho