也許你試圖向後定義FK。
這個SQL只是正常
create table student (
ID int identity not null primary key
,Name varchar(20) not null unique nonclustered
)
create table teacher(
ID int identity not null primary key
,Name varchar(20) not null unique nonclustered
);
create table dependents(
ID int identity not null primary key clustered
,StudentID int references student(ID)
,TeacherID int references teacher(ID)
unique nonclustered (StudentID,TeacherID)
);
insert student(Name) values ('Fred'),('George');
insert teacher(Name) values ('Minerva'),('Severus');
insert dependents(StudentID,TeacherID)
select
student.ID,teacher.ID
from (values
('Fred', 'Minerva')
,('George','Minerva')
,('Fred', 'Severus')
)d(StudentName,TeacherName)
join student on student.Name = d.StudentName
join teacher on teacher.Name = d.TeacherName;
select
StudentName = student.Name
,TeacherName = teacher.Name
from dependents
join student on student.ID = dependents.StudentID
join teacher on teacher.ID = dependents.teacherID
drop table dependents;
drop table teacher;
drop table student;
處理,得到所希望的:
StudentName TeacherName
-------------------- --------------------
Fred Minerva
Fred Severus
George Minerva
爲什麼你認爲它不會工作?當你嘗試時發生了什麼? –
「這意味着弱實體會有兩個外鍵:來自兩個強實體的主鍵。」它會顯示爲空的學生在尋找教師時,反之亦然....不是很好的做法IMO – xirokx