如何在MYSQL中设计外键值为空的表?

如何在MYSQL中设计外键值为空的表?,mysql,sql,foreign-keys,Mysql,Sql,Foreign Keys,我正在尝试设计一个包含两个表的数据库项目和学生 Student | StudentID | ProjectID | |-----------|-----------| | 1 | NULL | | 2 | 1 | Student表记录每个学生选择的项目,学生只能选择project表中存在的项目 但是,当学生第一次报名上课时,我想将他的信息插入student表中,但当时他还没有选择任何项目,因此ProjectID将为空 当我将Stud

我正在尝试设计一个包含两个表的数据库<代码>项目和
学生

Student

| StudentID | ProjectID |
|-----------|-----------|
| 1         | NULL      |
| 2         | 1         |

Student
表记录每个学生选择的项目,学生只能选择
project
表中存在的项目

但是,当学生第一次报名上课时,我想将他的信息插入
student
表中,但当时他还没有选择任何项目,因此
ProjectID
将为空

当我将
Student-ProjectID
作为外键时,这是不允许的,因为
NULL
Project
中不存在


我该怎么办?

只需在可为空的列上声明一个外键:

create table students (
    . . . 
    projectID int,   -- nullable by default
    constraint fk_students_project foreign key (projectID) references projects(projectID)
);

当然,您需要首先创建
projects
表,这样外键声明才有效。

MySQLs确实允许在包含外键的列上使用NULL值

如果您收到一条错误消息,则很可能列被声明为NOT NULL,或者类似NULL值的内容被作为varchar提交


通常情况下,你会有一张学生表、一张项目表,以及一张相互关联的表“这是不允许的”你为什么这么认为?请阅读SQL FKs的工作原理。在考虑提问之前,请进行合理的研究,包括手册和指南。请不要问重复的问题。请参阅,其他链接,点击谷歌的“stackexchange家庭作业”和投票箭头鼠标悬停文本。
create table students (
    . . . 
    projectID int,   -- nullable by default
    constraint fk_students_project foreign key (projectID) references projects(projectID)
);