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

时间:2015-12-15 16:54:48

标签: mysql foreign-keys composite-primary-key mysql-error-1005

我担心的表格:

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;

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

这意味着链接表剧院和Price,我必须添加

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

代码仍然有效。

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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;