简体   繁体   English

多个表的数据库约束

[英]Database constraint over multiple tables

Say I have the following tables: 说我有以下表格:

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

The table ReplacedDayInWeek contains a day in a specific week that's replaced by another day. 表ReplacedDayInWeek包含特定周的一天,由另一天替换。

How can I create a SQL constraint (or perhaps another SQL based solution) that makes sure I can only insert rows into DayInWeek with a DayId that's part of the same week as WeekId ? 我如何创建一个SQL约束(或者可能是另一个基于SQL的解决方案),以确保我只能在DayInWeek插入与DayId同一周的WeekId

I'm looking for a solution with the least amount of changes to the source database. 我正在寻找对源数据库进行最少量更改的解决方案。 I'd prefer an additional table or table changes above stored procedures. 我更喜欢在存储过程之上更改一个表或表。

This data structure makes no sense to me. 这种数据结构对我来说毫无意义。 You have the mapping between days and weeks in two tables. 您有两个表中的天和周之间的映射。

You should really only be storing the week in one table and looking it up in the other. 你应该只将一周存储在一个表中,然后在另一个表中查找。

That said, you can do what you want using an additional constraint on day/week between the two tables: 也就是说,您可以使用两个表之间的日/周额外约束来执行您想要的操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM