检查数据库db2中的约束

时间:2015-10-04 01:36:52

标签: sql database db2 entity constraints

我正在设计一个数据库,其中包括以下实体:

create table Director(
    ID integer not null,
    YearsExperience integer not null,
    StudioAffiliation varchar(30),
    NetWorth REAL,
    primary key (ID)
);

create table Movie(
    ID varchar(20) not null,
    Title varchar(40) not null,
    Genre char(1) not null,
    ReleaseDate date not null,
    Earning real not null,
    primary key (ID)
);

现在导演和电影有两种关系:Direct和WonAward。后者是用他/她指导的电影记录导演是否赢得奖励或更多奖励:

create table Directs(
    DirectorID integer not null,
    MovieID varchar(20) not null,
    primary key (DirectorID, MovieID),
    foreign key (DirectorID) references Director (ID) on delete cascade,
    foreign key (MovieID) references Movie (ID) on delete cascade
);

create table WonAward(
    DirectorID integer not null,
    MovieID varchar(20) not null,
    AwardName varchar(30) not null,
    Year integer not null,
    Budget REAL not null,
    primary key (DirectorID, MovieID),
    foreign key (DirectorID) references Director (ID) on delete cascade,
    foreign key (MovieID) references Movie (ID) on delete cascade
);

我需要确保导演只为他/她指导的电影获奖。现在我尝试使用Check来实现这一点,但它在WonAward关系结束时继续给出以下2个条件的错误:

check (DirectorID = (SELECT DirectorID FROM Directs WHERE Directs.MovieID = MovieID)),
 check (MovieID = (SELECT MovieID FROM Directs WHERE Directs.DirectorID = DirectorID))

这是我不断得到的错误:

DB21034E  The command was processed as an SQL statement because it was not a 
valid Command Line Processor command.  During SQL processing it returned:
SQL0548N  A check constraint or generated column that is defined with "SELECT" 
is invalid.  SQLSTATE=42621

如果没有这些限制条件,我发现用户可以进入一个数据库,获得导演的奖励,这部电影不是由他们指导的。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

您无法创建查询相关行外数据的检查约束。您可以做的是创建一个BEFORE TRIGGER来验证条件是否得到满足。 CREATE TRIGGER documentation中有一些示例可以根据您的需求进行定制。

答案 1 :(得分:0)

定义从WonAwardDirects的外键,而不是:

create table WonAward(
    DirectorID integer not null,
    MovieID varchar(20) not null,
    AwardName varchar(30) not null,
    Year integer not null,
    Budget REAL not null,
    primary key (DirectorID, MovieID),
    foreign key (DirectorID, MovieID) references Directs
);