我这里有4张桌子:

CREATE TABLE paper (
id VARCHAR(20) PRIMARY KEY,
name VARCHAR(30)
) ENGINE =INNODB;

CREATE TABLE subscriber (
id VARCHAR(10) PRIMARY KEY,
name VARCHAR(20),
address VARCHAR(30),
suburb VARCHAR(20),
state VARCHAR(3),
postcode VARCHAR(4))
round_id INTEGER NOT NULL,
FOREIGN KEY (round_id) REFERENCES round (id)
   ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE = INNODB;

CREATE TABLE current_order (
paper_id VARCHAR(20),
subscriber_id VARCHAR(10),
PRIMARY KEY (paper_id, subscriber_id),
FOREIGN KEY (paper_id) REFERENCES paper (id)
   ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY(subscriber_id) REFERENCES subscriber (id)
   ON UPDATE CASCADE ON DELETE RESTRICT)
ENGINE = INNODB;

CREATE TABLE receipt (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
receipt_date DATE,
paid_till_date DATE,
paper_id VARCHAR(20),
subscriber_id VARCHAR(10))
ENGINE = INNODB;


现在,表格纸具有一个主键ID,在表格current_order中由paper_id引用。
表订户有一个主键ID,表current_order中的subscriber_id引用了它。
Tabe current_order具有复合主键(paper_id,subscriber_id)。
因此,这三个表已通过外键关系链接在一起。

如果我想将最后一张收据与这三个表链接起来,该怎么做?我的想法是
1:设置引用表current_order中的复合主键(paper_id,subscriber_id)的复合外键(paper_id,subscriber_id)。
2:在表current_order中分别设置两个单独的外键(paper_id)和(subscriber_id),分别引用(paper_id)和(subscriber_id)。

两种方法均无效,并且出现错误1452:无法添加或更新子行。
所以我真的很想知道在表收据和表current_order之间设置关系的正确方法是什么?
这是E-R Digram:

E-R DIGRAM

表收据和表current_order之间有两个链接,我需要据此设置关系。

最佳答案

我不是mysql专家,但我会尝试这样做:

CREATE TABLE receipt (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
receipt_date DATE,
paid_till_date DATE,
paper_id VARCHAR(20),
subscriber_id VARCHAR(10),
FOREIGN KEY (paper_id,subscriber_id) REFERENCES current_order (paper_id,subscriber_id)
   ON UPDATE CASCADE ON DELETE RESTRICT)
ENGINE = INNODB;


它有效吗?

关于mysql - 复合外键添加失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32990263/

10-12 13:10