两个表之间的表的SQLite组合键

时间:2017-11-21 19:40:17

标签: sqlite composite-key

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

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

然而,当我收到错误“foriegn key mismatch - CAR_DAMAGE引用WORKSHOP时出现问题。

我正在使用SQLite,因为我被迫使用它,由我的大学给出。

2 个答案:

答案 0 :(得分:1)

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

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

[更一般地说,根据所提供的信息,您的主要关键似乎比他们需要的更复杂:为什么不将WORKSHOP_ID作为WORKSHOPDAMAGE_ID的PK作为CAR_DAMAGE的PK?但也许你有充分的理由。]

答案 1 :(得分:0)

谢谢。此方法有效。因此,当我继续进行时,出现了一个新问题。表CAR_DAMAGE链接到第四个表(称为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个表组合为1,使用不同的主键吗? CAR_DAMAGE的主键是:

PRIMARY KEY(DAMAGE_KEY,CUSTOMER_ID,WORKSHOP_ID)