两个 table 之间 table 的 SQLite 组合键

SQLite composite key for a table between two tables

我正在尝试连接三个表。其中两个有主键,第三个应该 link 到。我需要这个中间值,因为它 linked 到第四个(但这工作正常)。我写的代码如下:

CREATE TABLE CUSTOMERS(
CUSTOMER_ID INT(10) NOT NULL, 
SURNAME CHAR(50) NOT NULL, 
NAME CHAR(50) NOT NULL,
PRIMARY KEY (CUSTOMER_ID)
);

CREATE TABLE WORKSHOP(
WORKSHOP_ID INT(10) NOT NULL,
NAME CHAR(100) NOT NULL, 
CHAIN_NAME CHAR(100),
CHAIN_ID INT(10),
CONTRACT_WORKSHOP CHAR(5) NOT NULL,
PRIMARY KEY (WORKSHOP_ID, CHAIN_ID)
);

CREATE TABLE CAR_DAMAGE(
DAMAGE_ID INT(10)  NOT NULL, 
CUSTOMER_ID INT(10) NOT NULL, 
DATE INT(20) NOT NULL, 
PLACE CHAR(128) NOT NULL,
WORKSHOP_ID INT(10) NOT NULL,
PRIMARY KEY (DAMAGE_ID, CUSTOMER_ID, WORKSHOP_ID, DATE, PLACE),
FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS (CUSTOMER_ID),
FOREIGN KEY (WORKSHOP_ID) REFERENCES WORKSHOP (WORKSHOP_ID)
);


INSERT INTO CUSTOMERS VALUES (1, "OLSEN", "TROND");
INSERT INTO CUSTOMERS VALUES (2, "JOHNSEN", "FELIX");
INSERT INTO CUSTOMERS VALUES (3, "SVINDAL", "AKSEL");
INSERT INTO CUSTOMERS VALUES (4, "BJORGEN", "MARIT");
INSERT INTO CUSTOMERS VALUES (5, "SVENDSON", "LISA");

INSERT INTO WORKSHOP VALUES (1, "BERTEL", "MOLLER", 1, "YES");
INSERT INTO WORKSHOP VALUES (2, "OLOF", "OLOF AUTO", 3, "NO");
INSERT INTO WORKSHOP VALUES (3, "J-AUTO", "MOLLER", 1, "YES");
INSERT INTO WORKSHOP VALUES (4, "SPEED", "BIRGER N. HAUG", 2, "YES");
INSERT INTO WORKSHOP VALUES (5, "RELAX AUTO", "MOLLER", 1, "YES");

INSERT INTO CAR_DAMAGE VALUES (1, 1, 10102008, "HELLERUD", 1);
INSERT INTO CAR_DAMAGE VALUES (2, 2, 14032015, "JAR", 2);
INSERT INTO CAR_DAMAGE VALUES (3, 3, 24052016, "LOMMEDALEN", 3);
INSERT INTO CAR_DAMAGE VALUES (4, 4, 31102017, "FLAKTVEIT", 4);
INSERT INTO CAR_DAMAGE VALUES (5, 5, 08062016, "STOCKHOLM", 5);

但是,当我收到错误“外键不匹配 - CAR_DAMAGE 引用 WORKSHOP。

时,问题就出现了

我正在使用 SQLite,因为我被迫使用它,这是我的大学提供的。

Table WORKSHOP 有一个复合主键 (WORKSHOP_ID, CHAIN_ID)。任何引用 table 的外键必须是复合外键,由相同的两个字段组成。因此,您需要将 CHAIN_ID 添加到 table WORKSHOP 并将您的外键声明更改为:

FOREIGN KEY (WORKSHOP_ID, CHAIN_ID) REFERENCES WORKSHOP (WORKSHOP_ID, CHAIN_ID)

[更一般地说,根据给定的信息,您的主键似乎比它们需要的更复杂:为什么不将 WORKSHOP_ID 作为 WORKSHOP 和 [=17= 的 PK ]作为CAR_DAMAGE的PK?但也许你有充分的理由。]

谢谢。这个方法奏效了。因此,当我继续时,出现了一个新问题。 table CAR_DAMAGE 链接到第四个 table(称为 DAMAGE_INFORMATION),代码为:

CREATE TABLE DAMAGE_INFORMATION(
DAMAGE_ID INT(10) NOT NULL, 
DAMAGE_TYPE CHAR(100) NOT NULL, 
DAMAGE_SIZE CHAR(50) NOT NULL, 
SPEND INT(10) NOT NULL, 
FOREIGN KEY (DAMAGE_ID) REFERENCES CAR_DAMAGE (DAMAGE_ID)
);

而且我收到与之前相同的错误,即外键不匹配 "DAMAGE_INFORMATION" 引用 "CAR_DAMAGE"。

难道不能把3个table组合成1个,不同的主键? CAR_DAMAGE的主键是:

主键(DAMAGE_KEY、CUSTOMER_ID、WORKSHOP_ID)