多个表的数据库约束

时间:2019-04-19 10:18:36

标签: sql sql-server

说我有以下表格:

CREATE TABLE [Weeks] 
(
    [Id] INT NOT NULL IDENTITY,
    CONSTRAINT [PK_Weeks] PRIMARY KEY ([Id])
);

CREATE TABLE [Days] 
(
    [Id] INT NOT NULL IDENTITY,
    [WeekId] INT NULL,

    CONSTRAINT [PK_Days] PRIMARY KEY ([Id]),
    CONSTRAINT [FK_Days_Weeks_WeekId] 
        FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id])
);

CREATE TABLE [ReplacedDayInWeek] 
(
    [Id] INT NOT NULL IDENTITY,
    [WeekId] INT NOT NULL,
    [DayId] INT NOT NULL,
    [ReplacedDayId] INT NOT NULL,

    CONSTRAINT [PK_ReplacedDayInWeek] PRIMARY KEY ([Id]),
    CONSTRAINT [FK_ReplacedDayInWeek_Days_DayId] 
        FOREIGN KEY ([DayId]) REFERENCES [Days] ([Id]),
    CONSTRAINT [FK_ReplacedDayInWeek_Weeks_WeekId] 
        FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id]),
    CONSTRAINT [FK_ReplacedDayInWeek_Weeks_ReplacedWeekId] 
        FOREIGN KEY ([ReplacedWeekId]) REFERENCES [Weeks] ([Id])
);

ReplacedDayInWeek表包含特定星期中的某一天,该日期将替换为另一天。

如何创建一个SQL约束(或者也许是另一个基于SQL的解决方案),以确保我只能将DayInWeek插入行到DayId中,而该行与{{1} }?

我正在寻找对源数据库所做的更改最少的解决方案。我希望在存储过程之上进行其他表或表更改。

1 个答案:

答案 0 :(得分:2)

这个数据结构对我来说毫无意义。您有两个表中的天和周之间的映射。

您实际上应该只将一周存储在一个表中,然后在另一个表中查找。

也就是说,您可以在两个表之间使用日/周的附加约束来执行所需的操作:

CREATE TABLE [Days] 
(
    [Id] INT NOT NULL IDENTITY,
    [WeekId] INT NULL,

    CONSTRAINT [PK_Days] PRIMARY KEY ([Id]),
    CONSTRAINT [FK_Days_Weeks_WeekId] 
        FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id]),
    CONSTRAINT UNQ_Days_WeekId_Id UNIQUE (WeekId, Id)
);

CREATE TABLE [DaysInWeek] 
(
    [Id] INT NOT NULL IDENTITY,
    [WeekId] INT NOT NULL,
    [DayId] INT NOT NULL,

    CONSTRAINT [PK_DaysInWeek] PRIMARY KEY([Id]),
    CONSTRAINT [FK_DaysInWeek_Days_WeekId_DayId] 
        FOREIGN KEY (WeekId, DayId) REFERENCES Days(WeekId, Id),
    CONSTRAINT [FK_DaysInWeek_Weeks_WeekId] 
        FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id])
);