我有一张 table
CREATE TABLE [dbo].[CoursesOfferedToBatches] (
[CourseId] VARCHAR (50) NOT NULL,
[Batch] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Batch] ASC, [CourseId] ASC),
CONSTRAINT [FK_OfferedCourses_ToCourses] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Courses] ([Id]),
CONSTRAINT [FK_CoursesOfferedToBatches_ToBatches] FOREIGN KEY ([Batch]) REFERENCES [dbo].[Batches] ([Id])
);
当我将 CourseId 作为外键从上表导出到下表时,如下所示,它在表后给出如下所示的错误
CREATE TABLE [dbo].[StudentsRegisterToCoursesOffered]
(
[StudentId] UNIQUEIDENTIFIER NOT NULL ,
[CourseId] VARCHAR(50) NOT NULL,
PRIMARY KEY ([CourseId], [StudentId]),
CONSTRAINT [FK_StudentsRegisterToCoursesOffered_ToStudents] FOREIGN KEY ([StudentId]) REFERENCES [Students]([StudentId]),
CONSTRAINT [FK_StudentsRegisterToCoursesOffered_ToCoursesOffered] FOREIGN KEY ([CourseId]) REFERENCES [CoursesOfferedToBatches]([CourseId])
)
错误:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[CoursesOfferedToBatches]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
我的问题到此结束,但为了引用,我添加了所有相关表格:
CREATE TABLE [dbo].[Courses] (
[Id] VARCHAR (50) NOT NULL,
[Name] VARCHAR (100) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Students] (
[StudentId] UNIQUEIDENTIFIER NOT NULL,
[DepartmentName] VARCHAR (50) NOT NULL,
[Address] VARCHAR (250) NULL,
[TwitterLink] VARCHAR (100) NULL,
[FacebookLink] VARCHAR (100) NULL,
[MemberSince] DATETIME NULL,
[ProfileViews] BIGINT DEFAULT ((0)) NULL,
[CNIC] CHAR (15) NULL,
[AboutMe] VARCHAR (3000) NULL,
PRIMARY KEY CLUSTERED ([StudentId] ASC),
CONSTRAINT [FK_Students_ToStudents] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[Users] ([UserId]),
CONSTRAINT [FK_Students_ToDepartments] FOREIGN KEY ([DepartmentName]) REFERENCES [dbo].[Departments] ([Name])
);
CREATE TABLE [dbo].[Batches] (
[Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
最佳答案
表 CoursesOfferedToBatches
需要有自己的主键,您已将其创建为复合键 PRIMARY KEY CLUSTERED ([Batch] ASC, [CourseId] ASC)
.正是这个复合键将成为 StudentsRegisterToCoursesOffered
中的外键,而不仅仅是 CourseId
。
关于mysql - 将外键从多对多关系导出到另一个表sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952000/