MySQL - 来自一个表的许多外键

时间:2016-10-06 18:22:03

标签: mysql sql

即时为游戏制作数据库...问题是我对数据库知之甚少。这是我的表格,我有问题:

CREATE TABLE items(
name VARCHAR(30) PRIMARY KEY,
type VARCHAR(20) NOT NULL,
atk INT,
def INT,
arm INT,
price_buy SMALLINT UNSIGNED,
price_sell SMALLINT UNSIGNED);

CREATE TABLE equipment (
id_eq INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
head_s VARCHAR(30),
body_s VARCHAR(30),
right_s VARCHAR(30),
left_s VARCHAR(30),
feet_s VARCHAR(30),
slot1 VARCHAR(30),
slot2 VARCHAR(30),
slot3 VARCHAR(30),
slot4 VARCHAR(30),
slot5 VARCHAR(30),
slot6 VARCHAR(30),
slot7 VARCHAR(30),
slot8 VARCHAR(30),
slot9 VARCHAR(30),
slot10 VARCHAR(30).
FOREIGN KEY (head_s) REFERENCES items(name),
FOREIGN KEY (body_s) REFERENCES items(name),
FOREIGN KEY (right_s) REFERENCES items(name),
FOREIGN KEY (left_s) REFERENCES items(name),
FOREIGN KEY (feet_s) REFERENCES items(name),
FOREIGN KEY (slot1) REFERENCES items(name),
FOREIGN KEY (slot2) REFERENCES items(name),
FOREIGN KEY (slot3) REFERENCES items(name),
FOREIGN KEY (slot4) REFERENCES items(name),
FOREIGN KEY (slot5) REFERENCES items(name),
FOREIGN KEY (slot6) REFERENCES items(name),
FOREIGN KEY (slot7) REFERENCES items(name),
FOREIGN KEY (slot8) REFERENCES items(name),
FOREIGN KEY (slot9) REFERENCES items(name),
FOREIGN KEY (slot10) REFERENCES items(name));

我对这个解决方案有疑问,有人能告诉我这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

一般情况下,这不是正确的方法,除非您有7个标记为1到7的插槽,并且您正在将项目放入部分或全部。

更典型的方式是联结表:

create table EquipmentItems (
    EquipmentItemId int primary key auto_increment,
    EquipmentId int,
    ItemId int,
    constraint fk_equipmentitems_equipment foreign key (EquipementId) references Equipement(id_eq),
    constraint fk_equipmentitems_item foreign key (ItemId) references items(ItemId)
);

如果你仔细看一下,你会注意到我在Items添加了一个合成密钥。这对于外键引用是一个好主意,因为整数通常比字符串更紧凑。