将外键从多个到多个关系导出到另一个表sql

时间:2015-11-27 07:10:12

标签: mysql sql

我有一张桌子

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])
)

错误:

  

由于验证错误,无法继续更新。请更正   如果出现以下错误,请重试。

     

SQL71516 ::引用的表' [dbo]。[CoursesOfferedToBatches]'   不包含与引用匹配的主键或候选键   外键中的列列表。如果引用的列是计算的   专栏,应该坚持下去。

我的问题在这里结束,但作为参考我添加了所有相关的表格:

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)
);

1 个答案:

答案 0 :(得分:0)

CoursesOfferedToBatches需要有自己的主键,您已将其创建为复合键PRIMARY KEY CLUSTERED ([Batch] ASC, [CourseId] ASC)。这个复合键是StudentsRegisterToCoursesOffered中的外键,而不仅仅是CourseId