2

我有这样的数据库方案..

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

我在这里做错了什么特别的事情吗?

4

1 回答 1

1

ALTER TABLE语法中所述:

CHECK子句被所有存储引擎解析但忽略。请参阅第 13.1.17 节,“<code>CREATE TABLE 语法”</a>。接受但忽略语法子句的原因是为了兼容性,以便更容易地从其他 SQL 服务器移植代码,以及运行使用引用创建表的应用程序。请参阅第 1.8.5 节,“MySQL 与标准 SQL 的区别”</a>。

你有几个选择:

  1. 使用FOREIGN KEY约束,这要求所有表都使用InnoDB存储引擎:

    ALTER TABLE Specialty
      ADD FOREIGN KEY (photographer) REFERENCES Photographer (id);
    
    ALTER TABLE Photo
      ADD FOREIGN KEY (takenBy, type) REFERENCES Specialty (photographer, type);
    
  2. 使用触发器:

    CREATE TRIGGER foo1 BEFORE INSERT ON Photo FOR EACH ROW
    IF NOT EXISTS (
      SELECT *
      FROM   Specialty s JOIN Photographer p ON s.photographer = p.id
      WHERE  p.id = NEW.takenBy AND s.type = NEW.type
    ) THEN CALL raise.error;
    
    CREATE TRIGGER foo2 BEFORE UPDATE ON Photo FOR EACH ROW
    IF NOT EXISTS (
      SELECT *
      FROM   Specialty s JOIN Photographer p ON s.photographer = p.id
      WHERE  p.id = NEW.takenBy AND s.type = NEW.type
    ) THEN CALL raise.error;
    
于 2012-10-21T07:11:16.157 回答