Sql 为什么初始化外键时出错?

Sql 为什么初始化外键时出错?,sql,sql-server,Sql,Sql Server,在这里,我从teacher_detils表初始化外键时出错。这里我使用SQLServer作为数据库 错误是-引用的表“教师详细信息”中没有与外键“fk_考试详细信息”中的引用列列表匹配的主键或候选键。 Msg 1750,16级,状态0,第43行 无法创建约束或索引。请参阅前面的错误 create table teacher_details( teacher_user_id varchar(30) not null, teacher_name varchar(60) not nul

在这里,我从teacher_detils表初始化外键时出错。这里我使用SQLServer作为数据库

错误是-引用的表“教师详细信息”中没有与外键“fk_考试详细信息”中的引用列列表匹配的主键或候选键。 Msg 1750,16级,状态0,第43行 无法创建约束或索引。请参阅前面的错误

create table teacher_details(
    teacher_user_id varchar(30) not null,
    teacher_name varchar(60) not null,
    teacher_email varchar(50) not null,
)

/*Alter teacher_details table for primary key*/


alter table teacher_details
add constraint pk_teacher_details primary key (teacher_user_id, teacher_email)

/* Table for exam */

create table exam_details(
    exam_id varchar(30) not null,
    teacher_user_id varchar(30) not null,
)

/* edited the drop table command to avoid confusion*/

/*Alter exam_details for primary key*/

alter table exam_details
add constraint fk_exam_details FOREIGN KEY (teacher_user_id)
    REFERENCES teacher_details(teacher_user_id)

错误是因为您试图在外键中引用非PK列teacher\u user\u id,因为teacher\u details有一个由两列组成的复合键-id和email

如果一个教师用户id可以有多个电子邮件id,那么我建议您在教师详细信息表中设置教师id PK

create table teacher_details(
    teacher_user_id varchar(30) not null,
    teacher_name varchar(60) not null
)

/*Alter teacher_details table for primary key*/


alter table teacher_details
add constraint pk_teacher_details primary key (teacher_user_id)
并创建一个单独的表来保存教师用户id的电子邮件:

create table teacher_emails(
    id int identity(1,1) primary key,
    teacher_user_id varchar(30) not null,
    teacher_email varchar(50) not null
)

alter table teacher_emails
add constraint fk_teacher_emails 
    FOREIGN KEY (teacher_user_id) REFERENCES teacher_details(teacher_user_id)
现在您可以按照您尝试的方式创建此FK:

/* Table for exam */

create table exam_details(
    exam_id varchar(30) not null,
    teacher_user_id varchar(30) not null,
)

/* edited the drop table command to avoid confusion*/

/*Alter exam_details for primary key*/

alter table exam_details
add constraint fk_exam_details FOREIGN KEY (teacher_user_id)
    REFERENCES teacher_details(teacher_user_id)
如果情况并非如此,即每个用户id只能有一封唯一的电子邮件,则不需要额外的电子邮件表。只需使用:

create table teacher_details(
    teacher_user_id varchar(30) not null,
    teacher_name varchar(60) not null,
    teacher_email varchar(50) unique not null
)

alter table teacher_details
add constraint pk_teacher_details primary key (teacher_user_id)

在上一条语句中,您已经删除了exam_details表。所以alter table query没有可运行的表。我已在教师详细信息表中将techer_user_id初始化为主键。Drop命令用于删除表,因为出现错误。之后,我创建了表,然后应用了约束。当我在JSP中验证教师注册表单时,我是否必须同时签入表teacher\u details和teacher\u tables?是的,但是如果您担心性能的话,这应该没问题。问题是,教师用户id可能会在很多地方使用,最好将其作为PK保存。你的意思是说,我将创建一个表来存储教师详细信息,另一个表来存储电子邮件id和密码,并将教师用户id作为外键?@Dinesh-是的,如果每个教师用户id可以有多封电子邮件。这不是你放置首先在PK约束中使用电子邮件列?如果我将对教师电子邮件使用唯一约束,并对教师用户id使用主键约束,那么这是否合适?因为老师可以更新电子邮件,因为它不是主键。如果我的项目没有为每个用户提供多个电子邮件id的选项