我有这样的数据库方案..
create table Photographer(
id int primary key references Person(id) on update cascade on delete cascade,
livesIn int not null references Location(id) on update cascade on delete no action
);
create table Specialty(
photographer int references Photographer(id) on update cascade on delete cascade,
type enum('portrait','landscape','sport'),
primary key(photographer, type)
);
create table Photo(
id int primary key,
takenAt timestamp not null,
takenBy int references Photographer(id) on update cascade on delete no action,
photographedAt int references Location(id) on update cascade on delete no action,
type enum('portrait','landscape','sport')
);
如果摄影师有 t 作为摄影师的专业之一,我必须限制数据库,以便摄影师有资格拍摄类型 t 的照片。
我的尝试没有奏效。
/*Attempt 1*/
ALTER TABLE Photo ADD CONSTRAINT constraint_1
CHECK (Photo.type in (SELECT Specialty.type FROM Specialty,Photo,Photographer
WHERE Photo.takenBy = Photographer.id
AND Photographer.id = Specialty.photographer
AND Specialty.type = Photo.type));
/*Attempt 2 using exists instead of 'in'*/
ALTER TABLE Photo ADD CONSTRAINT constraint_1
CHECK (exists (SELECT * FROM Specialty,Photo,Photographer
WHERE Photo.takenBy = Photographer.id
AND Photographer.id = Specialty.photographer
AND Specialty.type = Photo.type));
我在这里做错了什么特别的事情吗?