我正在使用MySQL Workbench而且由于某种原因我遇到了让FK限制工作的问题。
这是我用来测试外键约束是否有效的MySQL代码。
create table users(user_id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(20) NOT NULL, password VARCHAR(20) NOT NULL);
create table posts(user_id INT NOT NULL, CONSTRAINT fk_posts_user_id FOREIGN KEY(user_id) REFERENCES users(user_id), post_id INT PRIMARY KEY AUTO_INCREMENT, post_content VARCHAR(2000) NOT NULL, number_comments INT NOT NULL);
create table comments(user_id INT NOT NULL, CONSTRAINT fk_comments_user_id FOREIGN KEY(user_id) REFERENCES users(user_id), post_id INT NOT NULL, CONSTRAINT fk_comments_post_id FOREIGN KEY(post_id) REFERENCES posts(post_id), comment_id INT PRIMARY KEY, comment_content VARCHAR(2000) NOT NULL);
insert into users VALUES(NULL, "user1", "pass1");
insert into posts VALUES(4, NULL, "content1", 0);
我已经查看过有关此事的其他帖子,我尝试了以下内容:
有什么我想念的吗?谢谢!