复合主键的外键和另一个属性

Foreign Key of Composite Primary Key and Another Attribute

我关注的table:

CREATE TABLE Branch(
    branchID        varchar(5) PRIMARY KEY,
    branchName      varchar(100),
    city            varchar(100),
    phone           varchar(15)
)Engine=InnoDB;

CREATE TABLE Theatre(
    theatreID       varchar(5),
    branchID        varchar(5),
    theatreType     varchar(50),
    rowCapacity     INT,
    seatCapacity    INT,

    FOREIGN KEY(branchID) REFERENCES Branch(branchID),
    PRIMARY KEY(theatreID,branchID)
)Engine=InnoDB;

CREATE TABLE Day(
    dayID           varchar(4) PRIMARY KEY,
    dayName         varchar(20),
    dayPrice        int
)Engine=InnoDB;

CREATE TABLE Price(
    theatreID       varchar(5),
    branchID        varchar(5),
    theatreType     varchar(50),
    moviePrice      INT,
    dayID           varchar(4),
    FOREIGN KEY(theatreID,branchID,theatreType) 
        REFERENCES Theatre(theatreID,branchID,theatreType),
    FOREIGN key(dayID) REFERENCES Day(dayID),
    PRIMARY KEY(branchID,dayID,theatreType)
)Engine=InnoDB;

我了解到引用具有复合主键的 table 的外键需要具有所述复合主键的所有属性。

这意味着 link table 剧院和价格,我必须添加

FOREIGN KEY(theatreID,branchID) 
        REFERENCES Theatre(theatreID,branchID)

代码仍然有效。

但是,如果我想添加另一个外键,'theatreType'。它 returns 错误 1005。

    FOREIGN KEY(theatreID,branchID,theatreType) 
        REFERENCES Theatre(theatreID,branchID,theatreType)

我哪里做错了? 提前致谢。

外键和引用键需要具有相同的结构。如果您按以下方式更新 Theatre table,它将起作用

CREATE TABLE Theatre(
    theatreID       varchar(5),
    branchID        varchar(5),
    theatreType     varchar(50),
    rowCapacity     INT,
    seatCapacity    INT,

    FOREIGN KEY(branchID) REFERENCES Branch(branchID),
    PRIMARY KEY(theatreID,branchID,theatreType)
)Engine=InnoDB;