复合主键作为外键

piwo6bdm  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(566)

我有一张table

TABLE PARTECIPATION
(PARTY_ID INT,
GUEST ...
PRIMARY KEY(PARTY_ID, GUEST)
FOREIGN KEY(PARTY_ID) REFERENCES PARTY(ID)
FOREIGN KEY(GUEST) REFERENCES GUEST(GUEST)
)

还有一桌客人

TABLE GUEST
(NAME VARCHAR(20),
SURNAME VARCHAR(20),
AGE INT,

PRIMARY KEY(NAME, SURNAME)
)

现在,如何将partecipation的guest元素设置为guest表的外键引用?
我应该在guest named,idk,id中创建一个列并将其设置为主键吗?或者我可以这样做:

TABLE PARTECIPATION
(PARTY_ID INT,
GUEST_NAME VARCHAR(20),
GUEST_SURNAME VARCHAR(20)
PRIMARY KEY(PARTY_ID, GUEST_NAME, GUEST_SURNAME)
FOREIGN KEY(PARTY_ID) REFERENCES PARTY(ID),
FOREIGN KEY(GUEST_NAME) REFERENCES GUEST(NAME),
FOREIGN KEY(GUEST_SURNAME) REFERENCES GUEST(SURNAME))
vdzxcuhz

vdzxcuhz1#

外键必须具有与其引用的主键相同的列数和顺序。这意味着您必须将多列放入一个外键定义中,如果pk有多列。

TABLE PARTECIPATION
(PARTY_ID INT,
GUEST_NAME VARCHAR(20),
GUEST_SURNAME VARCHAR(20)
PRIMARY KEY(PARTY_ID, GUEST_NAME, GUEST_SURNAME)
FOREIGN KEY(PARTY_ID) REFERENCES PARTY(ID),
FOREIGN KEY(GUEST_NAME, GUEST_SURNAME) REFERENCES GUEST(NAME, SURNAME))

相关问题