这里我在从teacher_detils表初始化外键时遇到错误。这里我使用sql-server for database
错误是 - 引用的表'teacher_details'中没有主键或候选键与外键'fk_exam_details'中的引用列列表匹配。 Msg 1750,Level 16,State 0,Line 43 无法创建约束或索引。查看以前的错误。
a2lix_translation_form:
templating: "AcmeBundle:Translatable:template.html.twig"
答案 0 :(得分:0)
该错误是因为您尝试在外键中引用非PK列teacher_user_id,因为,teacher_details具有两列的复合键--id和email。
如果teacher_user_id可以有多个email_id,那么我建议您在teacher_details表中使用教师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)
并创建一个单独的表来保存teacher_user_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)
如果不是这种情况,即每个user_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)